Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Object-oriented PythonSeniorOccasionalPerformance

What does defining `__slots__` on a class do, and what trade-off does it introduce?

Answer

By default, every instance gets its own `__dict__` to hold arbitrary attributes, which is flexible but has real per-instance memory overhead. Defining `__slots__ = ("x", "y")` tells Python to allocate a fixed-size structure for exactly those named attributes instead of a per-instance dict, which meaningfully reduces memory usage when you create very many instances of a small class. The trade-off is that instances of a slotted class can no longer have arbitrary new attributes added at runtime — but only if nothing in the class hierarchy still provides a `__dict__`: if a base class defines no `__slots__` at all, or a subclass's own `__slots__` includes `"__dict__"`, instances still get one and the memory benefit is lost for that hierarchy. Multiple inheritance with slots from more than one non-empty base class is also restricted.

Strong answer includes

  • without slots every instance carries a flexible per-instance dict
  • slots allocate a fixed structure, cutting memory for many small instances
  • the no-new-attributes restriction only holds if nothing in the hierarchy still provides a __dict__

Practical example

A class holding millions of small coordinate objects can cut its memory footprint substantially by adding

Python example
__slots__ = ("x", "y")

, at the cost of

Python example
point.label = "origin"

now raising an AttributeError.

#performance#memory#slots

Sources

Data modelPython Software Foundation · Dunder methods, object identity, attribute lookup and the descriptor and context manager protocols