Sub topic 7
Controlling attribute access with properties
This chapter assumes you can write a class with __init__ and instance methods, and that you know the difference between instance and class attributes. You should also be comfortable with decorators as syntax: @name above a function. You don't need to know how decorators are built.
Why properties exist
Python code normally reads and writes attributes directly: dog.name, dog.age = 4. That is simple, but sooner or later a class needs a rule. Temperatures can't go below absolute zero. A total should always equal the sum of its parts. A field has to be renamed without breaking callers.
Many languages handle this by making every attribute private and writing getX() and setX() from day one. Python takes the opposite approach. Start with a plain attribute. If you later need control, turn it into a property without changing how callers use it.
A property is an attribute whose reads, writes, and deletes run your functions. The calling code still writes t.celsius = 20, but Python runs your validation code.
The basic pattern
Here is the property example from this tutorial's plan, with the failure cases shown.
class Temperature:
def __init__(self, celsius):
self.celsius = celsius # goes through the setter
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("temperature below absolute zero")
self._celsius = value
@property
def fahrenheit(self):
return self._celsius * 9 / 5 + 32
t = Temperature(100)
print(t.fahrenheit) # 212.0
t.celsius = 0
print(t.fahrenheit) # 32.0
try:
t.celsius = -300
except ValueError as exc:
print("rejected:", exc)
try:
t.fahrenheit = 50
except AttributeError as exc:
print("read-only:", exc)
print(t.celsius) # still 0Four things happen here:
@propertyturns the function below it into the getter. The attribute is now calledcelsius, and readingt.celsiuscalls that function.@celsius.setterattaches a second function to the same name. It runs on every assignment tot.celsius.- The real value lives in
self._celsius. A leading underscore is a convention meaning "internal, don't touch from outside." It is not enforced. fahrenheithas a getter but no setter, so it is read-only. Assigning to it raisesAttributeError.
The rejected assignment leaves the old value in place, because the setter raised before it reached self._celsius = value. Validate first and store last, so a failure never leaves the object half-updated.
What happens on assignment
Validation in `__init__`
Notice that __init__ assigns self.celsius = celsius, not self._celsius = celsius. This detail matters. Assigning through the public name sends the starting value through the same validation as every later change.
class Loose:
def __init__(self, celsius):
self._celsius = celsius # bypasses the setter
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("temperature below absolute zero")
self._celsius = value
bad = Loose(-500) # no error: the invalid value got in anyway
print(bad.celsius) # -500This is the most common property bug. The class looks protected, but the constructor leaves a hole. Use the public name inside __init__ whenever a setter does validation.
The infinite recursion trap
The setter must store the value under a different name than the property. If you reuse the name, the setter calls itself.
class Broken:
@property
def size(self):
return self.size # calls this getter again
@size.setter
def size(self, value):
self.size = value # calls this setter again
b = Broken()
try:
b.size = 1
except RecursionError:
print("RecursionError: the setter called itself")Inside a property function, self.size is not the stored value. It is the property, so the call recurses until Python gives up. The fix is a separate storage name, such as _size.
Computed attributes
A property doesn't need stored data behind it. It can compute its answer on each read, which keeps derived values consistent with their sources.
import math
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value <= 0:
raise ValueError("radius must be positive")
self._radius = value
@property
def area(self):
return math.pi * self._radius ** 2
@property
def diameter(self):
return 2 * self._radius
@diameter.setter
def diameter(self, value):
self.radius = value / 2 # reuse the radius validation
c = Circle(1)
print(round(c.area, 2)) # 3.14
c.diameter = 10
print(c.radius) # 5.0
print(round(c.area, 2)) # 78.54area can never go stale, because no _area is stored. diameter is writable and delegates to the radius setter, so it follows the same rules. There is exactly one place that holds the radius.
Expensive computations
A property recomputes on every access. If the work is costly and the inputs don't change, use functools.cached_property. It runs the function once per instance and stores the result in the instance dictionary.
from functools import cached_property
class Report:
def __init__(self, rows):
self.rows = rows
@cached_property
def total(self):
print("computing...")
return sum(self.rows)
r = Report([1, 2, 3])
print(r.total) # computing... then 6
print(r.total) # 6, no recomputationA cached_property never goes stale on its own. If rows changes later, total keeps the old value until you delete it with del r.total. Use a plain property when the inputs can change.
Deleters
A property can also react to del obj.attr. This is rarely needed, but it completes the set of getter, setter, and deleter.
class Session:
def __init__(self, token):
self._token = token
@property
def token(self):
return self._token
@token.deleter
def token(self):
print("token cleared")
self._token = None
s = Session("abc123")
del s.token
print(s.token) # NoneProperties and inheritance
A property belongs to the class, so a subclass inherits it like any other attribute. To change only the setter in a subclass, build a new property from the parent's with @Parent.name.setter. The new function can call the parent's original through fset.
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("temperature below absolute zero")
self._celsius = value
class ClampedTemperature(Temperature):
@Temperature.celsius.setter
def celsius(self, value):
Temperature.celsius.fset(self, max(value, -273.15))
print(ClampedTemperature(-500).celsius) # -273.15Because Temperature.__init__ assigns self.celsius, it picks up the subclass's setter for ClampedTemperature objects. This works only because the parent's constructor used the public name. If a subclass defines only @property def celsius, it silently replaces the whole property and drops the setter. Reads still work, but assignment then fails.
How properties work
A property is a descriptor: an object stored on the class that defines __get__, __set__, or __delete__. When you write t.celsius, Python finds celsius on type(t), sees that it is a descriptor, and calls its __get__ instead of looking in the instance dictionary. This explains several behaviors:
- Properties work only when defined on the class. Assigning a property object to an instance attribute does nothing special.
- Accessing
Temperature.celsiuson the class returns the property object itself. That is what makesTemperature.celsius.fsetpossible. - A property with a setter is a data descriptor. It takes priority over a same-named entry in the instance dictionary. Without a setter, a
cached_propertycan store its result in the instance dictionary and win on later reads. That is how it avoids recomputing.
When to use a property, and when not to
| Situation | Choice |
|---|---|
| Plain data with no rules | A normal attribute |
| A value needs validation or conversion on assignment | A property with a setter |
| A value is derived from other attributes | A read-only property |
| A derived value is expensive and its inputs never change | `cached_property` |
| The operation is slow, has side effects, or can fail in surprising ways | A method, such as `load()` |
| The same validation is needed on many attributes | A custom descriptor (outside this chapter) |
Callers read an attribute and expect it to be cheap and free of side effects. A property that hits the network or writes a file breaks that expectation. A method name with parentheses signals that real work is happening.
Common errors
- Setter bypassed in
__init__. Assign toself.public_name, notself._public_name. - Same name for storage and property. This causes
RecursionError. Store under an underscored name. - Decorator order.
@name.settermust come after the@propertythat definesname, and the setter function must use the same name. A different function name creates an unrelated attribute. - No setter, but code assigns. You get
AttributeError. That is intended for read-only values, but it is a bug if you forgot the setter. - Stale cache.
cached_propertydoes not notice changed inputs.
Exercise
A class Account stores a balance. Its __init__ runs self._balance = opening and the class defines a balance setter that rejects negative values. Why can Account(-50) still succeed, and what one-line change fixes it?
Show answer
__init__ assigns directly to _balance, so it skips the setter and never runs the negative check. Change the line to self.balance = opening so the starting value goes through the setter.
Exercise
Write a class Rectangle with width and height properties that reject values of zero or less, plus a read-only area property. What happens if code runs rect.area = 10?
Show answer
One solution is a class with __init__(self, width, height) that sets self.width = width and self.height = height. Each of width and height has a getter returning _width or _height and a setter that raises ValueError if value <= 0. area is a getter-only property returning self._width * self._height. Running rect.area = 10 raises AttributeError, because area has no setter.