Sub topic 9
Computed properties derived from other attributes
This chapter assumes you can define classes and use __init__, you know the @ decorator syntax, and you have read the earlier chapters on the @property getter and read-only properties. Here you will use a getter to calculate a value from other attributes each time it is read.
The problem with storing derived values
A rectangle has a width and a height. Its area follows from those two numbers. A first attempt often stores the area as another attribute:
class StaleRectangle:
def __init__(self, width, height):
self.width = width
self.height = height
self.area = width * height
s = StaleRectangle(3, 4)
print(s.area) # 12
s.width = 10
print(s.area) # 12, but the real area is now 40The object now holds three facts that must agree, and nothing makes them agree. Any code that changes width or height must also remember to update area. When it forgets, the object contradicts itself and no error is raised.
The fix is to store only the facts that cannot be derived (width and height) and compute everything else on demand.
A computed property
A computed property is a getter whose return value is calculated from other attributes each time it is read. It has no storage of its own.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@property
def area(self):
return self.width * self.height
@property
def perimeter(self):
return 2 * (self.width + self.height)
r = Rectangle(3, 4)
print(r.area) # 12
print(r.perimeter) # 14
r.width = 10
print(r.area) # 40
print(r.perimeter) # 28area and perimeter cannot go stale because they are recalculated on every read. Callers still write r.area, not r.area(), so the class reads like a plain data object.
Since there is no setter, these properties are also read-only. r.area = 5 raises AttributeError, which is usually what you want for a value that is defined by other values.
Computed values are not in the instance dictionary
A stored attribute lives in the instance's __dict__. A property lives on the class, so a computed value does not appear in the instance's dictionary:
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@property
def area(self):
return self.width * self.height
r = Rectangle(3, 4)
print(vars(r)) # {'width': 3, 'height': 4}
print("area" in vars(r)) # False
print(hasattr(r, "area")) # True
print(r.area) # 12This matters when you serialize an object with vars(obj) or obj.__dict__. Computed values will be missing, and you must add them yourself if the output needs them.
Combining several attributes
Computed properties are not limited to arithmetic. They are also useful for formatting and for summarizing a collection:
class Order:
def __init__(self, customer, lines):
self.customer = customer
self.lines = lines # list of (name, unit_price, quantity)
@property
def total(self):
return sum(price * qty for _, price, qty in self.lines)
@property
def item_count(self):
return sum(qty for _, _, qty in self.lines)
@property
def summary(self):
return f"{self.customer}: {self.item_count} items, total {self.total:.2f}"
order = Order("Ada", [("pen", 1.5, 4), ("notebook", 3.25, 2)])
print(order.summary) # Ada: 6 items, total 12.50
order.lines.append(("stapler", 7.0, 1))
print(order.summary) # Ada: 7 items, total 19.50Appending to lines changed summary with no extra code. One property can also use another, as summary does with total and item_count. Each read of summary recalculates both.
A computed property with a setter
A computed value can accept assignment as long as the setter writes back to the stored attributes. The setter translates the new value into changes to the real state. Here the stored value is _degrees, and fahrenheit is a second way to read and write it:
class Celsius:
def __init__(self, degrees):
self.degrees = degrees
@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
@fahrenheit.setter
def fahrenheit(self, value):
self.degrees = (value - 32) * 5 / 9 # reuse the validating setter
t = Celsius(25)
t.fahrenheit = 212
print(t.degrees) # 100.0
try:
t.fahrenheit = -1000
except ValueError as exc:
print(exc) # temperature is below absolute zeroThe fahrenheit setter assigns to self.degrees, not to self._degrees. This sends the value through the validation in the degrees setter, so the rule is written once. Only one number is stored, so the two views cannot disagree.
Another common case is a value built from several parts, like a full name:
class Person:
def __init__(self, first, last):
self.first = first
self.last = last
@property
def full_name(self):
return f"{self.first} {self.last}"
@full_name.setter
def full_name(self, value):
parts = value.split()
if len(parts) != 2:
raise ValueError("expected a first and a last name")
self.first, self.last = parts
p = Person("Grace", "Hopper")
p.full_name = "Ada Lovelace"
print(p.first) # Ada
print(p.last) # LovelaceThe setter is where you decide what assignment means. If no sensible meaning exists, leave the setter out and keep the property read-only.
Stored, computed, and cached
| Approach | Where the value lives | Stays correct after inputs change | Cost per read |
|---|---|---|---|
| Plain attribute set in `__init__` | Instance `__dict__` | No, you must update it by hand | Very low |
| Computed `@property` | Nowhere, recalculated | Yes | Whatever the getter costs |
| `cached_property` | Instance `__dict__` after first read | No, unless you clear it | Low after the first read |
A computed property trades CPU time for correctness. For width * height the cost is trivial. For a sum over a million items, every read repeats the work. A later chapter covers functools.cached_property, which avoids the repeat but brings back the staleness problem from the first section.
Edge cases and common errors
Hidden cost
Callers treat attribute access as cheap. A getter that scans a large list, queries a database, or reads a file will surprise them, especially inside a loop:
for i in range(len(order.lines)):
if order.total > 100: # recalculates the whole sum on every pass
breakIf the work is slow, make it a method such as compute_total() so the call signals the cost, or cache it deliberately. A good rule: a property should be fast enough that no caller would think twice about reading it.
Side effects in a getter
A getter should not change the object, write files, or print. Debuggers, hasattr, and tools that inspect objects may read properties without the author expecting it. A getter that increments a counter or consumes an iterator will behave differently depending on who looks at it.
Leaking mutable internals
A computed property that returns an internal list lets callers change your state through the result:
class Playlist:
def __init__(self, titles):
self._titles = list(titles)
@property
def titles(self):
return tuple(self._titles) # a copy that cannot be mutated
pl = Playlist(["a", "b"])
print(pl.titles) # ('a', 'b')
try:
pl.titles.append("c")
except AttributeError:
print("tuples cannot be appended to")Returning a tuple (or a copy) keeps changes going through methods you control.
Exceptions raised inside the getter
An error in the getter appears at the line that reads the property. If lines contains a bad entry, then order.total raises, and so does anything that calls it, such as summary. Read the traceback from the bottom to find which attribute access failed.
Floating point results
Derived values built from floats carry rounding error, such as 0.1 + 0.2. Round for display (f"{x:.2f}"), not inside the getter, unless the rounded value is the correct one for your domain. For money, store integer cents or use decimal.Decimal.
Choosing what to store
Ask which values are the independent facts. Store those. Everything that can be calculated from them is a candidate for a computed property. In Rectangle, width and height are independent, so area is computed. In Celsius, the temperature is the fact, and both scales are views of it. Pick one as the stored value, and expose the other as a computed property with a setter if callers need to assign through it.
Exercise
A Triangle class stores base and height in __init__. Which of base, height, and area should be stored attributes and which should be a computed property? What happens if the code does t.area = 10 and why?
Show answer
Store base and height, and define area as a read-only @property returning self.base * self.height / 2. Then t.area is always correct after base or height changes. The assignment t.area = 10 raises AttributeError because the property has no setter, which prevents the object from holding an area that contradicts its base and height.
Exercise
In the Celsius class above, why does the fahrenheit setter assign to self.degrees instead of self._degrees?
Show answer
Assigning to self.degrees runs the validating degrees setter, so the below-absolute-zero check applies to Fahrenheit input too. Assigning to self._degrees would skip the check and let an invalid temperature be stored.
Exercise
A Report class has a property row_count that reads a 2-million-line file each time it is accessed, and a loop calls it on every iteration. Name two ways to improve the design.
Show answer
Turn it into a method such as count_rows() so the cost is visible to callers, or compute it once and keep the result with functools.cached_property (accepting that the value will not update if the file changes). Reading the count once into a local variable before the loop also removes the repeated work.