What is `__slots__` in a Python class and what are its trade-offs?

Python Developer Hard

Python Developer — Hard

What is `__slots__` in a Python class and what are its trade-offs?

Key points

  • `__slots__` lists allowed instance attributes
  • Saves memory by preventing __dict__ creation per instance
  • Faster attribute access but loses dynamic attribute addition
  • Requires explicit __weakref__ slot for weakref support
  • Can complicate inheritance

Ready to go further?

Related questions