Sub topic 13
The property() function and what the decorator does
This chapter assumes you can write a property with @property and @name.setter, and that you know a decorator is a function applied to the function below it. Here you will see that @property is shorthand for an ordinary call to the built-in property(). Knowing the call form explains several behaviors that look odd otherwise.
The decorator is a function call
A decorator line like @property means "call property with the function below, and bind the result to that function's name." These two forms are identical:
def width(self):
return self._width
width = property(width)@property
def width(self):
return self._widthproperty is a class, not a plain function. Calling it builds a property object that stores up to three functions plus a docstring. That object is a descriptor, a mechanism covered in the last chapter of this tutorial. For now, treat it as an object that Python consults when you read, assign, or delete the attribute.
The signature
property(fget=None, fset=None, fdel=None, doc=None)fgetis called asfget(obj)when you read the attribute.fsetis called asfset(obj, value)when you assign to it.fdelis called asfdel(obj)when you usedel.docbecomes the property's docstring.
Any argument you leave out is None. A missing fset makes assignment raise AttributeError, and a missing fdel does the same for deletion. This is why a getter-only property is read-only.
A property written in function form
Here is a Box class that uses the call form with no decorators:
class Box:
def __init__(self, width):
self.width = width # goes through the setter
def _get_width(self):
return self._width
def _set_width(self, value):
if value <= 0:
raise ValueError("width must be positive")
self._width = value
def _del_width(self):
print("deleting width")
del self._width
width = property(_get_width, _set_width, _del_width,
doc="Width of the box, must be positive.")
b = Box(3)
b.width = 10
print(b.width) # 10
print(Box.width.__doc__) # Width of the box, must be positive.
del b.width # deleting width
try:
Box(-1)
except ValueError as exc:
print(exc) # width must be positiveThe class body runs top to bottom. The three helper functions become ordinary class attributes first. Then property(...) runs and its result is bound to the name width. Python finds that object on the class whenever you use b.width, and it calls the right stored function.
You can inspect the stored pieces through the attributes fget, fset, fdel, and __doc__:
print(Box.width.fget.__name__) # _get_width
print(Box.width.fset.__name__) # _set_width
print(Box.width.fdel.__name__) # _del_widthReading Box.width on the class returns the property object itself. It does not call the getter, because there is no instance to pass in.
What @width.setter really does
The chain of decorators in a read/write property relies on one rule: a property object is immutable. Its methods getter, setter, and deleter each return a new property object that is a copy of the original with one function replaced.
p1 = property(lambda self: 1)
p2 = p1.setter(lambda self, value: None)
print(p1 is p2) # False
print(p1.fset) # None
print(p2.fset is not None) # TrueNow read the decorator form again:
class Box:
def __init__(self, width):
self.width = width
@property
def width(self):
return self._width
@width.setter
def width(self, value):
if value <= 0:
raise ValueError("width must be positive")
self._width = valueIt runs in this order:
@propertywraps the firstwidthfunction. The namewidthnow refers to a property with only a getter.- For the second definition, Python first evaluates the decorator expression
width.setter. It looks upwidthin the class namespace and finds the getter-only property. - The new function is defined and passed to
setter. That returns a new property with both getter and setter. - The name
widthis rebound to the new property. The old getter-only object is discarded.
Gotchas that follow from this
Both functions must use the same name
The second definition looks up the first by name, so the names have to match. If they differ, you get two separate attributes:
class Demo:
@property
def x(self):
return 1
@x.setter
def y(self, value):
print("set", value)
d = Demo()
print(d.x) # 1
d.y = 5 # set 5
print(d.y) # 1
try:
d.x = 5
except AttributeError:
print("x is still read-only")x.setter(...) returned a new property with getter and setter, and it was bound to y. The original x was never replaced, so it stays read-only.
The setter must come after the getter
@width.setter needs an existing width in the class namespace. If you write the setter first, you get a NameError. Likewise, if you define a plain method named width between the getter and the setter, the setter decorator will try to call .setter on the method and fail.
Helper functions stay visible in function form
In the Box example above, _get_width and _set_width remain as methods on the class. A leading underscore marks them as internal. If you want them gone, add del _get_width, _set_width at the end of the class body. The decorator form has no such leftovers, because every function is rebound to the same name.
The docstring comes from the getter
When you omit doc, property copies the docstring from fget. In the decorator form, put the docstring on the getter. A docstring on the setter is ignored.
Function form binds the exact functions
The property stores the function objects you gave it, not method names. A subclass that overrides _get_width will not change what the property calls:
class Wide(Box):
def _get_width(self):
return 99
print(Wide(3).width) # 3, not 99To make overriding work with the function form, wrap the call in a lambda that looks the method up at access time:
class FlexibleBox:
def __init__(self, width):
self._width = width
def _get_width(self):
return self._width
width = property(lambda self: self._get_width())
class WideBox(FlexibleBox):
def _get_width(self):
return 99
print(WideBox(3).width) # 99The next chapter covers inheritance and property overrides in more detail.
When the function form is the better tool
Decorators read better for a single property. The function form is useful when you build properties programmatically, because property(...) is an ordinary expression that you can return from a function:
def positive(name):
private = "_" + name
def getter(self):
return getattr(self, private)
def setter(self, value):
if value <= 0:
raise ValueError(f"{name} must be positive")
setattr(self, private, value)
return property(getter, setter, doc=f"Positive {name}.")
class Rect:
width = positive("width")
height = positive("height")
def __init__(self, width, height):
self.width = width
self.height = height
r = Rect(2, 5)
print(r.width, r.height) # 2 5
try:
r.height = 0
except ValueError as exc:
print(exc) # height must be positiveThis factory removes duplicated validation code. It also shows the limit of the approach. Each call creates two new closures, and the validation rule is hidden inside the factory. When you need the same rule on many attributes, a descriptor class (the last chapter) does this more cleanly.
Quick reference
| You write | Python does |
|---|---|
| `@property` on a method | Calls `property(method)` and binds the result to the method's name |
| `@name.setter` | Calls `name.setter(func)`, which returns a new property, and rebinds `name` |
| `@name.deleter` | Same pattern, replacing `fdel` |
| `property(g, s, d, doc)` | Builds the property object directly, with no name matching needed |
| `Class.name` | Returns the property object itself, so you can inspect `fget`, `fset`, `fdel` |
Exercise
A class defines @property def size(self) and then @size.setter def resize(self, value), where resize stores the value in self._size. What happens for obj.size = 5, and what happens for obj.resize = 5?
Show answer
obj.size = 5 raises AttributeError, because size is still the getter-only property. obj.resize = 5 works and calls the setter, because size.setter(...) returned a new property with getter and setter that was bound to the name resize.
Exercise
Rewrite the decorator-based Celsius.degrees property from earlier in this tutorial using the function form of property(), so that it keeps the same validation and has the docstring "Temperature in Celsius." How do you read the setter function back from the class afterwards?
Show answer
Define _get_degrees(self) returning self._degrees and _set_degrees(self, value) that raises ValueError when value < -273.15 and otherwise assigns self._degrees = value. Then write degrees = property(_get_degrees, _set_degrees, doc="Temperature in Celsius.") in the class body. Afterwards, Celsius.degrees.fset returns the setter function, and Celsius.degrees.__doc__ returns the docstring.