`__slots__`
__slots__ is a class attribute that names the instance fields the class will allow. Instances then skip __dict__ and store those fields in a compact layout, which saves memory and blocks accidental attributes.
Detailed Explanation
A normal instance has a __dict__: a dictionary that can grow with any attribute name. That is flexible and expensive. Each instance pays for a dict, and millions of small objects add up. __slots__ = ("sku", "qty") tells the type object to allocate fixed storage for those names instead.
Lookups for slotted attributes go through descriptors the class installed. Assignment to a name that is not in the slots raises AttributeError. That is a feature when you want a closed shape, and a surprise when a test sets order.debug = True.
Subclasses need their own __slots__. An empty __slots__ = () on the child keeps the compact layout. Omitting __slots__ on the child gives the child a __dict__ again, which defeats the memory win for that subclass. Multiple inheritance with two slotted parents is allowed only if at most one parent has a non-empty slot layout in a conflicting way; the interpreter raises TypeError when the layouts cannot be combined.
You lose some conveniences. copy.copy still works. Weak references require "__weakref__" in the slots if you need them. __dict__ is absent unless you add "__dict__" to the slots, which brings the dict back and is only useful when you want a mix of fixed and dynamic names.
Dataclasses can take slots=True (Python 3.10+) and generate __slots__ for you. That is the usual way to get the benefit without writing the tuple by hand.
Use slots when you will create a large number of small, long-lived objects (graph nodes, parsed rows, particles). Do not slot every class in an application. The readability and flexibility cost is real, and the memory win is negligible at dozens of instances.
Code Examples
class Order:
__slots__ = ("sku", "qty")
def __init__(self, sku: str, qty: int):
self.sku = sku
self.qty = qty
line = Order("A-1", 2)
print(line.sku, line.qty) # A-1 2
# line.note = "rush" # AttributeError: 'Order' object has no attribute 'note'
print(hasattr(line, "__dict__")) # Falseclass PriorityOrder(Order):
__slots__ = ("priority",) # required to stay slotted
def __init__(self, sku: str, qty: int, priority: int):
super().__init__(sku, qty)
self.priority = priority
print(PriorityOrder("A-1", 1, 5).priority)from dataclasses import dataclass
@dataclass(slots=True)
class Point:
x: int
y: int
print(Point(1, 2)) # Point(x=1, y=2)Common Gotchas
A subclass without `__slots__` grows a `__dict__`
you think the tree is compact and only the parent is. Add `__slots__ = ()` or more names on every child.
No weakrefs by default
caches that weakref instances need `"__weakref__"` in the slots.
Multiple slotted bases can fail at class creation
keep a single slotted ancestor, or follow the error and redesign.
Slots do not make the object immutable
you can still change `line.qty`. Use a frozen dataclass if you want assignment to fail.