Sub topic 9
property as a descriptor
This chapter assumes you know the descriptor protocol (__get__, __set__, __delete__) and the difference between data and non-data descriptors. It also assumes you know the lookup order of object.__getattribute__. Here you use that machinery to see that property is an ordinary class built on it.
What property is
property is a class. When you write @property above a method, you create an instance of property and store it in the class namespace under the method's name. That instance defines __get__, __set__ and __delete__, so it is a data descriptor. This holds even when you never define a setter.
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def celsius(self):
return self._celsius
t = Temperature(20)
print(type(Temperature.__dict__["celsius"]).__name__) # property
print(t.celsius) # 20
try:
t.celsius = 30
except AttributeError:
print("read-only: property defines __set__")The assignment fails because property.__set__ exists and raises AttributeError when no setter was supplied. The instance has a __dict__, but the data descriptor takes precedence over it, so the write never reaches the dict.
The lookup path for a property
Reading obj.celsius goes through the rules you already know. object.__getattribute__ searches the MRO of type(obj) and finds a property object. Because that object has __set__, it counts as a data descriptor and wins over the instance __dict__. Python then calls property.__get__(prop, obj, type(obj)), which calls the getter function with obj as its argument.
Three consequences follow.
- An entry named
celsiusint.__dict__is ignored on reads. It can only get there by writing to__dict__directly. - Every access runs Python code. A property is slower than a plain attribute, and it can raise exceptions or have side effects.
- Reading through the class, as in
Temperature.celsius, calls__get__(prop, None, Temperature). The property returns itself in that case, which lets you reachfget,fsetand__doc__for introspection.
A pure-Python model
The following class reproduces the behavior of property. It is a simplified model, but it makes the mechanics visible.
class MyProperty:
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
if doc is None and fget is not None:
doc = fget.__doc__
self.__doc__ = doc
self._name = getattr(fget, "__name__", "?")
def __set_name__(self, owner, name):
self._name = name
def __get__(self, obj, objtype=None):
if obj is None:
return self
if self.fget is None:
raise AttributeError(f"property {self._name!r} has no getter")
return self.fget(obj)
def __set__(self, obj, value):
if self.fset is None:
raise AttributeError(f"property {self._name!r} has no setter")
self.fset(obj, value)
def __delete__(self, obj):
if self.fdel is None:
raise AttributeError(f"property {self._name!r} has no deleter")
self.fdel(obj)
def getter(self, fget):
return type(self)(fget, self.fset, self.fdel, self.__doc__)
def setter(self, fset):
return type(self)(self.fget, fset, self.fdel, self.__doc__)
def deleter(self, fdel):
return type(self)(self.fget, self.fset, fdel, self.__doc__)
class Circle:
def __init__(self, radius):
self.radius = radius
@MyProperty
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("radius must be non-negative")
self._radius = value
c = Circle(2)
print(c.radius) # 2
c.radius = 5
c.__dict__["radius"] = 99 # bypasses __set__
print(c.radius) # 5, the data descriptor still wins
print(c.__dict__) # {'_radius': 5, 'radius': 99}
try:
c.radius = -1
except ValueError as exc:
print(exc) # radius must be non-negativeThe decorator syntax hides a detail. @radius.setter does not modify the existing property. It calls radius.setter(func), which returns a new property object holding the same getter plus the new setter. The name radius is then rebound to that new object. For this to work, the setter function must use the same name as the property. If you name it differently, the class ends up with two entries: a read-only property and a stray function.
Storage and the recursion trap
The getter and setter need somewhere to keep the value. The usual choice is a private attribute such as _radius, stored in the instance __dict__. The property itself holds no per-instance state. It only holds the functions.
The most common property bug is storing the value under the property's own name.
class Broken:
@property
def x(self):
return self.x # calls the property again
try:
Broken().x
except RecursionError:
print("RecursionError: getter reads the property it implements")Inside a getter, self.x is another trip through __getattribute__, which finds the same property and calls the same getter. A setter that does self.x = value recurses the same way. Always read and write a different name, usually one with a leading underscore.
Inheritance and overriding
A property is looked up through the MRO like any other class attribute, so subclasses inherit it. The getter function is stored inside the property object, which causes a gotcha: overriding the method in a subclass does not change what the property calls.
class A:
def _describe(self):
return "A"
@property
def label(self):
return self._describe()
class B(A):
def _describe(self):
return "B"
print(A().label) # A
print(B().label) # B, the getter calls self._describe(), which is overriddenHere the property works with subclassing because the getter delegates to a regular method that the subclass overrides. If the getter did its work inline, a subclass would need to replace the whole property. Writing a plain def label(self) in the subclass would replace the property with a function, and b.label would turn into a bound method. To extend only one part, reuse the inherited property object:
class Base:
@property
def size(self):
return 1
class Derived(Base):
@Base.size.setter
def size(self, value):
print("size set to", value)
d = Derived()
print(d.size) # 1
d.size = 10 # size set to 10Base.size returns the property object (the obj is None path). Calling .setter produces a new property for Derived and leaves Base.size unchanged.
Errors that hide behind `__getattr__`
If a getter raises AttributeError, object.__getattribute__ fails with AttributeError, and Python then calls __getattr__ if the class defines it. The original error message is lost.
class Ghost:
@property
def data(self):
return self._missing # not defined anywhere
def __getattr__(self, name):
print(f"__getattr__({name!r})")
raise AttributeError(name)
try:
Ghost().data
except AttributeError as exc:
print("error:", exc)The output is:
__getattr__('_missing')
__getattr__('data')
error: dataThe error names data, not _missing, so it points at the wrong attribute. If a property seems to "not exist" even though it is defined, check whether its getter raises AttributeError internally. Moving the failing code out of the getter or catching the exception there usually shows the real cause.
Practical guidance
| Situation | Choice |
|---|---|
| Validate or transform a value on assignment, once | `property` with a setter |
| Same validation on many attributes or classes | A custom descriptor with `__set_name__` |
| Read-only computed value | `property` with only a getter |
| Expensive value computed once per instance | `functools.cached_property` |
| Add behavior to an attribute in a stable public API | Start with a plain attribute, switch to `property` later |
The last row works because callers write obj.name in both cases, so the interface does not change when you add a property.
Summary of behaviors
propertyis a data descriptor, so it overrides any same-named entry in the instance__dict__.- A property with no setter still defines
__set__, which raisesAttributeError. - Accessing a property through the class returns the property object.
@x.setterand@x.getterreturn new property objects, and the setter function must reuse the namex.- The property holds functions, not data. Per-instance values live under a different name in the instance.
- An
AttributeErrorraised inside a getter can trigger__getattr__and hide the real error.
Exercise
A class defines @property def total(self) with a getter only. A script runs obj.__dict__["total"] = 5 and then print(obj.total). What does it print, and why? What happens if the script then runs obj.total = 7?
Show answer
It prints the value the getter returns, not 5. The property is a data descriptor, so it takes precedence over the instance __dict__ entry, and __get__ calls the getter. The assignment obj.total = 7 raises AttributeError because property.__set__ exists but no setter was defined, and the write never reaches the instance __dict__.
Exercise
This code raises RecursionError on Account(10). Explain why and fix it.
class Account:
def _init_(self, balance):
self.balance = balance
@property
def balance(self):
return self.balance
@balance.setter
def balance(self, value):
self.balance = value
Show answer
Both the getter and the setter use self.balance, which is the property itself. The assignment in __init__ calls the setter, which assigns self.balance again and calls the setter again, forever. The fix is to store the value under a different name: have the getter return self._balance and the setter assign self._balance = value.