ReviseAlgo Logo

Object-Oriented Programming

__slots__

Memory optimization and attribute control for classes

Interview: Performance topic — tests understanding of Python memory model, __dict__ overhead, and optimization techniques

Last Updated: June 12, 2026 6 min read

__slots__ is a class-level attribute that explicitly declares data members and prevents the creation of __dict__ and __weakref__ for instances. This saves significant memory and speeds up attribute access, making it essential when creating millions of objects.

How __slots__ Works

  • Replaces the per-instance __dict__ with a fixed-size array
  • Only declared attribute names are allowed
  • Attempting to set an undeclared attribute raises AttributeError
  • Saves ~40-50% memory per instance (no dict overhead)
  • Attribute access is slightly faster (direct offset vs hash lookup)

When to Use __slots__

  • Creating millions of small objects (data processing, game entities)
  • When you want to prevent accidental attribute creation
  • Performance-critical applications where attribute access is a bottleneck
  • Library/framework code where attribute set is fixed and well-defined

__slots__ and Inheritance

Each class in the hierarchy should define its own __slots__ for only the new attributes. Parent slots are inherited. If a child doesn't define __slots__, Python creates __dict__ for child instances (defeating the purpose).

Common Pitfall

Don't use __slots__ if you need dynamic attribute assignment, multiple inheritance with conflicting slots, or compatibility with libraries that use __dict__ (like some ORMs and serialization libraries).

Use Cases

Memory optimization when creating millions of objects (data processing, simulations)

Preventing accidental attribute creation in strict APIs

Game development: thousands of entities with fixed attribute sets

Network protocols: lightweight packet/message objects

Performance-critical code where attribute access speed matters

Common Mistakes

Forgetting to define __slots__ in child classes — defeats memory savings

Using __slots__ with libraries that require __dict__ (ORMs, serialization)

Trying to add dynamic attributes to slotted objects (AttributeError)

Declaring the same slot name in parent and child classes (wastes memory)

Using __slots__ on classes that genuinely need dynamic attributes