Sub topic 9
Computed properties derived from other attributes
This chapter assumes you can define classes, use __init__, read the @ decorator syntax, and raise and catch exceptions. It also assumes you have seen a basic @property getter.
What a computed property is
A computed property is a getter that calculates its value from other attributes each time you read it. The class stores no separate copy of the result. Callers write t.fahrenheit as if it were a stored attribute, but Python runs the method behind the scenes.
Storing a derived value in a second attribute is risky because the two can disagree. If you keep both degrees and fahrenheit as plain attributes and update only one, the object is inconsistent. A computed property avoids this, because there is only one source of truth.
A worked example
The Celsius class stores one value, _degrees. The fahrenheit property derives from it.
class Celsius:
def __init__(self, degrees):
self.degrees = degrees # runs the setter, so validation applies here too
@property
def degrees(self):
return self._degrees
@degrees.setter
def degrees(self, value):
if value < -273.15:
raise ValueError("temperature is below absolute zero")
self._degrees = value
@property
def fahrenheit(self):
return self._degrees * 9 / 5 + 32
t = Celsius(25)
print(t.degrees) # 25
print(t.fahrenheit) # 77.0
t.degrees = 30 # goes through the setter
try:
t.degrees = -300
except ValueError as exc:
print(exc) # temperature is below absolute zerofahrenheit has no setter, so it is also read-only. After t.degrees = 30, reading t.fahrenheit returns 86.0 with no extra work, because the getter reads the current _degrees every time.
How the lookup flows
Rules for good computed properties
- Derive from stored attributes only. Keep the single source of truth in one place.
- Keep the getter cheap and free of side effects. Callers expect attribute access to be fast and safe to repeat.
- Do not mutate state in a getter. Reading
t.fahrenheitshould never changet. - Leave out the setter unless the reverse calculation is well defined. A setter for
fahrenheitwould have to convert back to Celsius and run the same validation.
Common errors
Assigning to a computed property raises AttributeError, because a property with no setter is read-only. This is the intended behavior, but it surprises people who treat fahrenheit as stored data.
Another error is calling the property like a method. t.fahrenheit() fails, because t.fahrenheit is already the float 77.0, and a float is not callable.
A third error is putting slow work in the getter. If each read takes seconds, callers will read it in loops without knowing the cost. Use a method with a clear name, or a later tool such as cached_property, instead.
Choosing between a property and a method
Use a property when the value feels like a fact about the object, is cheap, and has no side effects. Use a method when the operation does work, takes arguments, or can fail in ways callers should anticipate. area on a rectangle suits a property. download_report() suits a method.
Exercise
A Rectangle class stores width and height as plain attributes. Write an area property that returns their product. What happens if you later set rect.width = 10 and read rect.area again, and what happens if you try rect.area = 50?
Show answer
Define @property def area(self): return self.width * self.height. After rect.width = 10, the next read of rect.area uses the new width, because the getter recalculates each time. Assigning rect.area = 50 raises AttributeError, because area has no setter and is read-only.
Exercise
Why is it a design mistake to store fahrenheit as a second plain attribute in Celsius and update it inside the degrees setter?
Show answer
Two stored values can drift apart, for example if some code writes _degrees or fahrenheit directly. A computed property keeps one source of truth, so the derived value is always consistent with it.