Python __slots__ and Descriptors
What you will learn
- How objects store attributes, and what
__slots__changes - The costs of slots, including inheritance
- What a descriptor is:
__get__,__set__,__set_name__ - Writing a reusable validated field
- How
property, methods andcached_propertyare descriptors
1. Where attributes live
By default, every object keeps its attributes in a dictionary, __dict__ (lesson 13.2). That is flexible: you can add new attributes any time. But a dictionary per object costs memory, and typos create new attributes silently.
class P:
def __init__(self, x, y):
self.x, self.y = x, y
p = P(1, 2)
print(p.__dict__)
p.z = 3
print(p.__dict__)
{'x': 1, 'y': 2}
{'x': 1, 'y': 2, 'z': 3}
2. slots
If you declare __slots__, listing the allowed attribute names, Python stores them in fixed slots and creates no __dict__:
class S:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x, self.y = x, y
s = S(1, 2)
print(hasattr(s, "__dict__"))
s.z = 3
False
AttributeError: 'S' object has no attribute 'z' and no __dict__ for setting new attributes
Two effects:
- Less memory per object. In one test I ran (100,000 objects with two attributes each, measured with
tracemalloc), the slotted version used about 1.5 times less memory. The exact saving depends on the Python version and the objects, so measure your own case. - No stray attributes. A misspelled
s.zz = 3raises an error instead of creating a new attribute.
Slots are useful when you create very many small objects. For most classes the saving is not worth the restrictions.
Quick check: can you add a new attribute to an instance of a class that defines `__slots__ = ("x",)`?
No, unless the slots include a __dict__ entry or a parent class without slots provides one. Otherwise AttributeError.
3. Costs and rules of slots
- Inheritance: a subclass without its own
__slots__gets a__dict__again, so the saving is lost. Declare__slots__in each subclass (listing only the new names):
class S2(S):
pass
s2 = S2(1, 2)
s2.extra = 1
print(hasattr(s2, "__dict__"))
class S3(S):
__slots__ = ("w",)
S3(1, 2).q = 1
True
AttributeError: 'S3' object has no attribute 'q' and no __dict__ for setting new attributes
- Unset slots raise
AttributeErrorwhen read, like missing attributes:
class Z:
__slots__ = ("a",)
Z().a
AttributeError: 'Z' object has no attribute 'a'
- Weak references need
"__weakref__"in the slots. - Class-level defaults with the same name as a slot are not allowed; set defaults in
__init__. - Dataclasses can do it for you:
@dataclass(slots=True)(lesson 13.11).
4. Descriptors: attributes with behaviour
In lesson 13.4, a property ran code when you read or set an attribute. Properties are built from a more general tool, the descriptor: an object, stored in a class attribute, with any of these methods:
| Method | Called when |
|---|---|
__get__(self, obj, owner) |
the attribute is read (obj.attr) |
__set__(self, obj, value) |
the attribute is assigned (obj.attr = v) |
__delete__(self, obj) |
the attribute is deleted |
__set_name__(self, owner, name) |
the class is created; tells the descriptor its own name |
A descriptor lets you write the logic once and reuse it for many attributes. Suppose three classes need "must be positive" checks. With properties you would write each check again; with a descriptor you write one class:
class Positive:
def __set_name__(self, owner, name):
self.name = "_" + name
def __get__(self, obj, owner=None):
if obj is None:
return self
return getattr(obj, self.name)
def __set__(self, obj, value):
if value <= 0:
raise ValueError(f"{self.name[1:]} must be positive")
setattr(obj, self.name, value)
class Item:
price = Positive()
qty = Positive()
def __init__(self, price, qty):
self.price, self.qty = price, qty
i = Item(5, 2)
print(i.price, i.qty)
print(i.__dict__)
i.price = -1
5 2
{'_price': 5, '_qty': 2}
ValueError: price must be positive
What happens:
- When the class
Itemis built, Python calls__set_name__on each descriptor with the name it was given ("price","qty"). self.price = pricefinds thatpricein the class is a descriptor with__set__, so it callsPositive.__set__, which validates and stores the real value under_pricein the object's__dict__.i.pricecallsPositive.__get__.- Accessed on the class (
Item.price),objisNone, and the descriptor returns itself.
The descriptor object is one per class attribute, shared by all instances. So the per-object data must be stored on the object (obj), never on self of the descriptor.
Data and non-data descriptors
- A data descriptor defines
__set__(or__delete__) as well. It wins over an instance attribute of the same name. - A non-data descriptor defines only
__get__. An instance attribute of the same name wins.
This difference is what lets a "lazy" attribute compute once and then be replaced by a plain value:
class Lazy:
def __init__(self, f):
self.f = f
self.name = f.__name__
def __get__(self, obj, owner=None):
if obj is None:
return self
v = self.f(obj)
obj.__dict__[self.name] = v
return v
class Data:
calls = 0
@Lazy
def total(self):
Data.calls += 1
return 42
d = Data()
print(d.total, d.total, Data.calls, "total" in d.__dict__)
42 42 1 True
The function ran once. After the first read, the value sits in d.__dict__["total"], which beats the non-data descriptor on later reads. The standard library offers this ready-made as functools.cached_property:
from functools import cached_property
class CP:
n = 0
@cached_property
def v(self):
CP.n += 1
return 7
c = CP()
print(c.v, c.v, CP.n)
7 7 1
5. You already use descriptors
Descriptors are everywhere in Python:
class K:
def m(self):
return 1
k = K()
print(K.m)
print(k.m)
print(K.__dict__["m"].__get__(k, K)())
print(type(property()).__name__, hasattr(property, "__get__"))
<function K.m at 0x000002A3B6C43EC0>
<bound method K.m of <__main__.K object at 0x000002A3B68CF620>>
1
property True
- Functions are non-data descriptors.
k.mcallsfunction.__get__(k, K), which returns a bound method withselffilled in. That is howselfgets passed. property,classmethod,staticmethodand slot members are all descriptors. (The addresses in the printed output differ on every run.)
@property is enough for one attribute in one class. Write a descriptor when the same rule is needed in many places or on many attributes.
6. When to use what
| Need | Tool |
|---|---|
| a check on one attribute | @property (lesson 13.4) |
| the same check on many attributes or classes | a descriptor |
| compute once, then reuse | functools.cached_property |
| millions of small objects, fixed attributes | __slots__ |
| record with automatic methods | @dataclass (add slots=True if needed) |
| validation of a whole model with many rules | a library, or plain methods |
Worked example: a validated student record
A reusable Field descriptor checks the type and an optional range. The Student class uses __slots__ (so no stray attributes) and three fields with different rules.
class Field:
def __init__(self, kind, low=None, high=None):
self.kind, self.low, self.high = kind, low, high
def __set_name__(self, owner, name):
self.label = name
self.store = "_" + name
def __get__(self, obj, owner=None):
if obj is None:
return self
return getattr(obj, self.store)
def __set__(self, obj, value):
if not isinstance(value, self.kind):
raise TypeError(f"{self.label} must be {self.kind.__name__}")
if self.low is not None and value < self.low:
raise ValueError(f"{self.label} must be at least {self.low}")
if self.high is not None and value > self.high:
raise ValueError(f"{self.label} must be at most {self.high}")
setattr(obj, self.store, value)
class Student:
__slots__ = ("_name", "_age", "_score")
name = Field(str)
age = Field(int, 5, 120)
score = Field(float, 0.0, 100.0)
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
def __repr__(self):
return f"Student({self.name!r}, {self.age}, {self.score})"
s = Student("Rina", 16, 88.5)
print(s)
s.score = 91.0
print(s.score)
for field, value in [("age", 200), ("score", "high"), ("name", 5)]:
try:
setattr(s, field, value)
except (TypeError, ValueError) as e:
print(type(e).__name__ + ":", e)
try:
s.nickname = "R"
except AttributeError as e:
print("AttributeError:", e)
print(hasattr(s, "__dict__"), Student.age.label)
Student('Rina', 16, 88.5)
91.0
ValueError: age must be at most 120
TypeError: score must be float
TypeError: name must be str
AttributeError: 'Student' object has no attribute 'nickname' and no __dict__ for setting new attributes
False age
| Part | Role |
|---|---|
Field |
one descriptor class, used three times with different rules |
__set_name__ |
learns the attribute name, so errors say age, not a generic message |
__slots__ = ("_name", ...) |
the hidden storage names (with the underscore); the public names are the descriptors |
| the loop | every bad assignment is refused with a clear message |
s.nickname = "R" |
refused: no __dict__ and no slot |
The values are made up. Note how the slots hold _name, _age, _score (what the descriptors store), while name, age, score are the class-level descriptors.
Common mistakes
- Storing per-object data on the descriptor itself (
self.value = v): all objects would share it. Store it onobj. - Forgetting
if obj is None: return selfin__get__, soClass.attrbreaks. - Subclassing a slotted class without
__slots__, which brings back__dict__. - Using slots for a handful of objects and getting only restrictions.
- Giving a slot the same name as a class attribute with a default.
- Using a descriptor where a simple
@propertywould do.
Key takeaways
- Objects normally keep attributes in
__dict__;__slots__replaces it with fixed slots, saving memory and blocking stray attributes. - Subclasses need their own
__slots__(listing only new names), or the__dict__returns. - A descriptor is a class-level object with
__get__,__set__or__delete__;__set_name__tells it its name. - Properties, methods,
classmethod,staticmethodandcached_propertyare all descriptors. - Use a descriptor to reuse one attribute rule across many attributes; keep per-object data on the object.
Practice
1. What does __slots__ = ("x", "y") prevent?
Show answer
Creating a per-object __dict__, and therefore adding any attribute other than x and y.
2. Why must a subclass of a slotted class declare its own __slots__?
Show answer
Without it, the subclass gets a normal __dict__ again and loses the memory saving and the restriction.
3. Which method tells a descriptor the name it was assigned to in the class?
Show answer
__set_name__(self, owner, name).
4. Why does a descriptor store values on obj and not on self?
Show answer
One descriptor object is shared by every instance of the class, so values stored on self would be shared by all objects.
5. What is the difference between a data and a non-data descriptor?
Show answer
A data descriptor defines __set__ or __delete__ and takes priority over an instance attribute of the same name. A non-data descriptor defines only __get__ and loses to an instance attribute.
6. How does k.m become a bound method?
Show answer
Functions are descriptors: function.__get__(k, K) returns a bound method with k filled in as self.