Loading…
A short voice session: one question, one follow-up, then instant feedback — up to 5 minutes.
__slots__ declares a fixed set of attributes so instances store them in a compact structure instead of a per-instance __dict__, saving memory and slightly speeding up access, at the cost of flexibility.
By default every instance has a dictionary for its attributes, which costs memory for each object. Defining slots = ('x', 'y') removes that dictionary, so creating millions of small objects, such as points or records, uses significantly less memory. The trade-offs are that you cannot add attributes not listed in slots, weak references need 'weakref' in slots, and every class in an inheritance chain must define slots to get the full benefit. Dataclasses support slots=True. It is an optimization to apply after measuring, not a default for every class.