Sub topic 9
Decorators you already have: lru_cache, property, staticmethod, classmethod
This chapter assumes you can write a basic decorator, know that @name means f = name(f), and have seen a decorator factory such as repeat(times=3). Python ships several decorators that use these ideas. Knowing them saves you from rewriting what the standard library already does.
lru_cache: remember results
functools.lru_cache is a decorator factory. It wraps a function and stores each result under the arguments that produced it. A repeated call with the same arguments returns the stored result instead of running the body again.
import functools
@functools.lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(50)) # 12586269025
print(fib.cache_info())Without the cache, the recursive version makes an exponential number of calls. With it, each value of n is computed once.
maxsize limits how many results are kept. When the cache is full, the least recently used entry is dropped. maxsize=None means no limit. functools.cache (Python 3.9+) is shorthand for that unlimited form.
The wrapper has extra attributes. fib.cache_info() reports hits and misses, and fib.cache_clear() empties the cache.
property: methods that look like attributes
property turns a method into an attribute. Reading obj.area calls the method, with no parentheses. A .setter lets you run validation on assignment.
import math
class Circle:
def __init__(self, radius):
self.radius = radius # goes through the setter
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("radius must be non-negative")
self._radius = value
@property
def area(self):
return math.pi * self._radius ** 2
c = Circle(2)
print(round(c.area, 2)) # 12.57
c.radius = 3
print(round(c.area, 2)) # 28.27@radius.setter works because @property replaced the name radius with a property object. That object has a setter method, which is itself a decorator. The setter must use the same name as the property, and it stores the value in a different attribute (_radius). area has no setter, so c.area = 1 raises AttributeError.
staticmethod and classmethod
Both change what a method receives as its first argument.
- A regular method receives the instance (
self). - A
classmethodreceives the class (cls). - A
staticmethodreceives nothing extra. It is a plain function that lives in the class namespace.
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
@classmethod
def from_string(cls, text):
year, month, day = map(int, text.split("-"))
return cls(year, month, day)
@staticmethod
def is_leap_year(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
d = Date.from_string("2024-02-29")
print(d.year, Date.is_leap_year(d.year)) # 2024 Truefrom_string is an alternative constructor. Because it calls cls(...) and not Date(...), a subclass calling Sub.from_string(...) gets a Sub object back. is_leap_year does not use the class or an instance, so it is a static method. It sits in the class only because it belongs with dates.
Choosing between them
| Decorator | Wraps | First argument | Typical use |
|---|---|---|---|
| `lru_cache` | function | none added | Cache pure computations |
| `property` | method | `self` | Computed or validated attributes |
| `classmethod` | method | `cls` | Alternative constructors |
| `staticmethod` | function | none added | Helper tied to a class by topic |
Exercise
You write @functools.lru_cache on a function total(items) and call total([1, 2, 3]). What happens, and how would you change the call so caching works?
Show answer
It raises TypeError: unhashable type: 'list', because the cache uses the arguments as dictionary keys and lists are not hashable. Pass a hashable value instead, for example total((1, 2, 3)) with a tuple.
Exercise
In the Date class, why does from_string use cls(year, month, day) instead of Date(year, month, day)?
Show answer
With cls, a subclass that calls from_string gets an instance of the subclass. Hard-coding Date would always return a Date.