Sub topic 9
property as a descriptor
This chapter assumes you know the descriptor protocol (__get__, __set__, __delete__), the difference between data and non-data descriptors, and the lookup order from the previous chapters.
property is a class, not magic
property is a built-in class that implements all three descriptor methods. Because it defines __set__, it is a data descriptor. Python therefore checks it before the instance __dict__, whether or not you wrote a setter.
class Temperature:
def __init__(self, celsius):
self._celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("below absolute zero")
self._celsius = value
t = Temperature(20)
t.celsius = 25
print(t.celsius) # 25
t.__dict__["celsius"] = "shadow"
print(t.celsius) # 25, the property still wins@celsius.setter does not change the existing property. It returns a new property that copies the getter and adds the setter. The name celsius is then rebound to that new object.
What property does internally
A pure-Python model shows the mechanism. The __get__ method passes the instance to the stored function. The __set__ and __delete__ methods do the same for fset and fdel. When one of those functions is missing, they raise AttributeError.
class MyProperty:
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
self.__doc__ = doc or getattr(fget, "__doc__", None)
def __get__(self, obj, objtype=None):
if obj is None:
return self
if self.fget is None:
raise AttributeError("property has no getter")
return self.fget(obj)
def __set__(self, obj, value):
if self.fset is None:
raise AttributeError("property has no setter")
self.fset(obj, value)
def __delete__(self, obj):
if self.fdel is None:
raise AttributeError("property has no deleter")
self.fdel(obj)
def setter(self, fset):
return type(self)(self.fget, fset, self.fdel, self.__doc__)
class Box:
def __init__(self, width):
self._width = width
@MyProperty
def width(self):
return self._width
@width.setter
def width(self, value):
self._width = value
b = Box(4)
b.width = 10
print(b.width) # 10
print(type(Box.width).__name__) # MyPropertyThe obj is None branch handles access through the class. Box.width returns the descriptor object itself, which lets tools inspect fget and the docstring.
Common errors
- Read-only by accident. A property with only a getter still defines
__set__. Assigning to it raisesAttributeErrorinstead of writing to the instance__dict__. - Infinite recursion. If the setter assigns to
self.celsius, it calls itself. Store the value under a different name, such asself._celsius. - Shadowing assumptions. Writing into
obj.__dict__["celsius"]has no effect on reads, because the data descriptor wins. - Overriding in subclasses. A property is a class attribute. A subclass that redefines
celsiusas a plain method or value replaces the whole property, including its setter. - Per-class, not per-attribute reuse. One property object serves every instance, so it must keep state on
obj, never on itself. This is the same pitfall as in custom descriptors.
Exercise
A class defines @property def size(self) with no setter. You run obj.__dict__["size"] = 5 and then print(obj.size). What is printed, and why does obj.size = 7 fail?
Show answer
It prints the value returned by the getter, not 5. A property defines __set__, so it is a data descriptor and takes precedence over the instance __dict__. For the same reason obj.size = 7 calls property.__set__, which raises AttributeError because no fset exists.