Sub topic 3
Property as a Descriptor
Assume you know Python classes, instances, inheritance, and basic dunder methods. A descriptor is a class attribute that controls access through methods such as __get__ and __set__.
Built-in descriptors
property is a data descriptor. Its getter runs when you read an attribute, and its setter runs when you assign one.
class Account:
def __init__(self, balance):
self._balance = balance
@property
def balance(self):
return self._balance
@balance.setter
def balance(self, value):
if value < 0:
raise ValueError("balance cannot be negative")
self._balance = value
account = Account(10)
account.balance = 20
print(account.balance)Because a property is a data descriptor, it takes priority over an entry with the same name in the instance dictionary.
classmethod and staticmethod are also descriptors. A class method binds the class as its first argument. A static method receives no automatic argument.
class User:
@classmethod
def anonymous(cls):
return cls("anonymous")
@staticmethod
def valid_name(name):
return bool(name.strip())
def __init__(self, name):
self.name = nameFallbacks and storage
__getattr__ runs only after normal lookup fails. It can provide computed defaults, but it should raise AttributeError for names it cannot handle.
__slots__ removes the normal instance __dict__ unless you include "__dict__". Each slotted name creates a member descriptor on the class. That descriptor stores the value in an internal slot.
functools.cached_property is a non-data descriptor. It computes a value once, then writes that value into the instance dictionary. A later lookup finds the instance value before the descriptor.
from functools import cached_property
class Report:
@cached_property
def total(self):
print("computing")
return sum(range(4))
report = Report()
print(report.total)
print(report.total)The output prints computing only once.
Class lookup and pitfalls
Class.name uses type.__getattribute__, not the instance lookup path. It may call a descriptor with obj=None. Metaclasses can customize class-level lookup.
Common mistakes include storing instance values on the descriptor itself, forgetting the obj is None case, and assuming every descriptor overrides instance attributes. Add logging to __get__ and inspect vars(type(obj)) when debugging.
Exercise
Why does a cached property return the cached value instead of recomputing?
Show answer
It is a non-data descriptor, so the value written to the instance dictionary wins on later lookups.