Sub topic 3
Computed Properties Derived from Other Attributes
Assume you know classes, __init__, basic decorators, and exceptions. A computed property calculates a value from current instance data instead of storing a separate copy.
Computed properties
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@property
def area(self):
return self.width * self.height
rectangle = Rectangle(4, 3)
print(rectangle.area) # 12
rectangle.width = 5
print(rectangle.area) # 15area looks like an attribute, but Python calls its getter method when you read it. It always reflects the current width and height.
When a plain attribute is better
Use a plain attribute when the value needs no validation, calculation, compatibility layer, or access control. A property adds behavior and can make simple data harder to understand. Do not create a property merely to wrap self._value if no behavior is needed.
Caching expensive values with `cached_property`
functools.cached_property computes a value once per instance, then stores the result. This is useful for expensive calculations whose inputs do not change.
from functools import cached_property
class Report:
def __init__(self, values):
self.values = values
@cached_property
def total(self):
print("computing")
return sum(self.values)
report = Report([2, 3, 5])
print(report.total) # computing, then 10
print(report.total) # 10If the inputs change, remove the cached value with del report.total before reading it again.
Deleting attributes with a deleter
A property can define a deleter with @name.deleter. Deleting the property then performs controlled cleanup.
class User:
def __init__(self, token):
self._token = token
@property
def token(self):
return self._token
@token.deleter
def token(self):
self._token = NoneThe `property()` function
Decorator syntax creates a property object. The equivalent function form is:
class Box:
def __init__(self, width):
self._width = width
def get_width(self):
return self._width
width = property(get_width)The full form accepts a getter, setter, deleter, and documentation string.
Overriding properties in subclasses
A subclass can replace or extend a property. Use super() when retaining the parent behavior.
class Square(Rectangle):
@property
def area(self):
return super().areaDescriptors: the mechanism behind `property`
A descriptor is an object that defines methods such as __get__, __set__, or __delete__. Python calls these methods during attribute access. property implements this descriptor protocol, which is why it can intercept reads, assignments, and deletion.
Exercise
Which tool should you choose for a costly value that should be calculated only once per instance?
Show answer
Use functools.cached_property. Delete the cached attribute when its source data changes.