What is __slots__ and when would you use it?hard

Type
conceptual
Topic
OOP & dunders
Frequency
common
Tags
slots, memory, OOP, performance
Answer

__slots__ replaces the per-instance __dict__ with a compact fixed array, saving 150–300 bytes per instance.

Explanation

By default every Python instance carries a __dict__ — a full hash map for that object's attributes. For classes instantiated millions of times (graph nodes, event records), this overhead is significant. __slots__ = ("x", "y") tells Python to use a fixed array instead. Trade-off: you can't add arbitrary attributes at runtime. Every class in the inheritance chain must define __slots__, or one missing class re-introduces a __dict__. In Python 3.10+, @dataclass(slots=True) is the cleanest way to get this.

Follow-upWhat happens to __slots__ in a subclass that doesn't define its own __slots__?