Sub topic 13
The property() function and what the decorator does
This chapter assumes you can write a class with __init__, use @property with a getter and setter, and read the @ decorator syntax. Here you will see that @property is a shortcut for an ordinary function call. Knowing this explains several confusing errors.
property() is a built-in class
property is a class. Its constructor takes up to four arguments: property(fget, fset, fdel, doc). Each is optional and defaults to None. You call it, then assign the resulting object to a name in the class body.
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
width = property(_get_width, _set_width, doc="Width of the box, must be positive.")
b = Box(3)
b.width = 10
print(b.width) # 10
try:
b.width = -1
except ValueError as exc:
print(exc) # width must be positive
print(Box.width.__doc__) # Width of the box, must be positive.The property object lives on the class. Python finds it when you read b.width, then calls fget(b). When you write b.width = 10, it calls fset(b, 10). Without a doc argument, the property takes its docstring from the getter.
What the decorator expands to
This decorated version builds the same property:
class Box:
def __init__(self, width):
self.width = width
@property
def width(self):
"""Width of the box, must be positive."""
return self._width
@width.setter
def width(self, value):
if value <= 0:
raise ValueError("width must be positive")
self._width = value
print(type(Box.width)) # <class 'property'>
print(Box.width.fget.__name__) # width
print(Box.width.fset is not None) # True
print(Box.width.fdel) # NoneThe steps run in order:
@propertycallsproperty(getter)and binds the result towidth.@width.settercallswidth.setter(new_function). That method returns a new property with the same getter plus the new setter.- The new property is bound to
widthagain, replacing the old one.
Each .setter, .getter, and .deleter call returns a copy and never modifies the original property. The decorator form is only a convenient way to write this sequence.
Common errors
The expansion explains these mistakes:
- Different name for the setter. If you write
@width.setterabovedef set_width(...), the new property is bound toset_width. The namewidthstill holds the read-only property, so assignment raisesAttributeError. - Setter defined before the getter.
@width.setterneedswidthto already exist as a property. Otherwise you get aNameError. - Using the function form in a loop or helper without a class. The property object must end up as a class attribute. Assigned to an instance attribute, it is just an inert object, because the lookup that triggers
fgetandfsetonly happens for attributes found on the class.
Choosing a form
| Situation | Prefer |
|---|---|
| New code with a getter and setter | Decorator form |
| Wrapping existing methods without renaming them | `property(fget, fset)` |
| Several attributes share one rule | A descriptor class, covered later in this tutorial |
Exercise
In a class body you write @property def size(self): ..., then @size.setter def set_size(self, v): .... What happens when you run obj.size = 5, and why?
Show answer
It raises AttributeError. The @size.setter call returns a new property with a setter, but that property is bound to the name set_size. The name size still refers to the original getter-only property, so assignment has no setter to call. Renaming the second method to size fixes it.