Descriptors
A descriptor is an object that customises attribute access by implementing __get__, __set__, or __delete__. Properties, methods, classmethod, and staticmethod are all descriptors.
Detailed Explanation
When you write order.sku, Python does not always return order.__dict__["sku"]. If the class has an attribute of that name whose type implements the descriptor protocol, that object gets to handle the access. __get__(self, instance, owner) runs for reads. __set__(self, instance, value) runs for writes. __delete__ runs for del.
A data descriptor defines __get__ and __set__ (or __delete__). It wins over an instance __dict__ entry of the same name. A non-data descriptor defines only __get__. An instance dict entry wins over it. Functions are non-data descriptors: their __get__ is what binds self and produces a bound method. If you store a function on the instance, it hides the method.
@property builds a data descriptor. @classmethod and @staticmethod wrap functions in descriptors that bind cls or bind nothing. __slots__ installs a data descriptor per name. Understanding descriptors is how those features stop looking like unrelated magic.
You write a descriptor when several classes need the same attribute behaviour: a validated field, a lazy cached value, a column in an ORM. The descriptor lives on the class. It uses the instance to store per-object state, typically under a private name (instance._cents) or in its own dict keyed by id (avoid that; it leaks). A descriptor on the class is shared; putting per-instance data on self of the descriptor would share it across instances.
__set_name__(self, owner, name) (3.6+) tells the descriptor the attribute name it was assigned to, so you do not repeat cents = Validated(name="cents").
Keep descriptors small. If the logic is used on one class, a property is enough. If you are building an ORM, you are in descriptor territory.
Code Examples
class NonNegative:
def __set_name__(self, owner, name: str) -> None:
self.public = name
self.private = "_" + name
def __get__(self, instance, owner):
if instance is None:
return self
return getattr(instance, self.private)
def __set__(self, instance, value: int) -> None:
if value < 0:
raise ValueError(f"{self.public} must be >= 0")
setattr(instance, self.private, value)
class Account:
cents = NonNegative()
def __init__(self, cents: int):
self.cents = cents # goes through __set__
acct = Account(100)
print(acct.cents) # 100
# acct.cents = -1 # ValueError# Functions are non-data descriptors: lookup on the instance binds self.
class Order:
def label(self) -> str:
return "order"
line = Order()
print(line.label) # <bound method Order.label ...>
print(Order.label) # <function Order.label ...>Common Gotchas
Storing per-instance state on the descriptor object
one descriptor is shared by all instances. Write to the instance, not to `self.value` on the descriptor.
Data vs non-data
a `__set__` makes the descriptor win over `__dict__`. Without `__set__`, an instance attribute hides it.
Looking up the descriptor on the class
`__get__(None, owner)` should return the descriptor or a class-level value, not assume an instance.
`property` is enough for one class
do not write a descriptor to validate a single field.