What is Python's __slots__?
Why Interviewers Ask This
Advanced questions like this reveal whether a candidate has internalized Python deeply enough to make architectural decisions. Strong answers demonstrate both breadth and depth of experience.
Answer
By default, Python objects store instance attributes in a __dict__ dictionary, which has significant memory overhead. Defining __slots__ in a class replaces the per-instance __dict__ with a fixed, compact layout in memory: class Point: __slots__ = ["x", "y"]; def __init__(self, x, y): self.x = x; self.y = y. Benefits: ~50-70% memory savings per instance (critical for classes with millions of instances, e.g., game objects, financial instruments), slightly faster attribute access. Limitations: cannot add attributes not listed in __slots__ (no dynamic attributes), cannot use __weakref__ unless added to slots, complicates multiple inheritance. Use slots for: data-heavy classes where you create many instances, when memory is a concern, and when the set of attributes is fixed. Python's dataclasses support slots with @dataclass(slots=True) (Python 3.10+).
Pro Tip
If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.