Skip to the solution
MediumDSA10 min read

What does __slots__ do?

51 views

The problem

Question presented to candidate: "Some classes in our codebase declare __slots__ = ('x', 'y'). What does that actually change about the objects, why would you do it, and what breaks when you do?"

What a strong answer should cover:

  • __slots__ declares a fixed set of attribute names; instances get fixed storage for them instead of a per-instance __dict__
  • Effects: less memory per object (no dict), and assigning an undeclared attribute raises AttributeError
  • How: each slot is a member descriptor on the class (type(Cls.__dict__['x']) is member_descriptor) that reads and writes a fixed offset in the object
  • Inheritance rules: every class in the chain must define __slots__ (only new names) or a __dict__ comes back; two bases with non-empty slots cannot be combined
  • Costs: no weak references unless '__weakref__' is listed, no class-attribute defaults with the same name, no vars() or cached_property; @dataclass(slots=True) (3.10+) generates them for you

Clarifying questions expected:

  • How many instances are alive at once? (the saving only matters with many objects)
  • Is the class part of a hierarchy, or used with weak references or cached_property?

Code / implementation expected: Optional β€” a slotted class next to a plain one showing the missing __dict__ and the AttributeError on a typo.

  • slots

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonNo __dict__, slot descriptors, unknown attributes rejected and the memory saving
PythonInheritance, __weakref__, __dict__ opt-in, layout conflicts and pickling

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 116 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

How do type hints work in Python?

Continue