slots

Normally each instance stores its attributes in its own dict, __dict__. That's flexible but costs memory, roughly a hundred extra bytes per object.

__slots__ = ("x", "y") tells Python the exact attribute names. Instances then get fixed slots and no __dict__. Two effects:

  • Less memory. This matters when you make millions of small objects.
  • A typo like s.z = 3 raises AttributeError instead of quietly making a new attribute.

With dataclasses, write @dataclass(slots=True).

Don't add slots everywhere. They're an optimisation for many small objects, and a good answer when an interviewer asks how to cut memory in a class with millions of instances.

Run it, then add "z" to the slots and run again.