Sub topic 9
Decorators You Already Have: lru_cache, property, staticmethod, classmethod
What this chapter assumes
You should already know how to write a basic decorator, what @ does, and why functools.wraps matters. This chapter looks at four decorators that ship with Python. Each is a good model for a different kind of decorator, and each has behavior you should know before relying on it.
| Decorator | Module | What it does | Kind |
|---|---|---|---|
| `lru_cache` | `functools` | Remembers results by arguments | Decorator factory (also usable bare) |
| `property` | built-in | Turns methods into attribute access | Class used as a decorator |
| `staticmethod` | built-in | Removes automatic argument binding | Class used as a decorator |
| `classmethod` | built-in | Binds the class instead of the instance | Class used as a decorator |
functools.lru_cache: memoization
Memoization means storing a function's results so that calling it again with the same arguments returns the stored value instead of recomputing it. lru_cache does this with a dictionary keyed by the call arguments. "LRU" means least recently used: when the cache is full, the entry that has gone unused longest is discarded.
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, fib(50) makes billions of recursive calls. With it, each value from 0 to 50 is computed once, so the work is linear.
lru_cache(maxsize=None) is a decorator factory, the same pattern as repeat(times=3). The call with its argument returns the real decorator. Since Python 3.8 you can also write @lru_cache with no parentheses, which uses the default maxsize=128. Since Python 3.9, functools.cache is a shortcut for lru_cache(maxsize=None).
Inspecting and clearing the cache
The wrapper that lru_cache returns carries extra attributes: cache_info(), which reports hits and misses, and cache_clear(), which empties the cache. This shows eviction at work:
import functools
@functools.lru_cache(maxsize=2)
def square(n):
return n * n
square(1) # miss
square(2) # miss
square(1) # hit, so 1 is now the most recently used
square(3) # miss, evicts 2 (the least recently used)
print(square.cache_info())
# CacheInfo(hits=1, misses=3, maxsize=2, currsize=2)
square.cache_clear()
print(square.cache_info())
# CacheInfo(hits=0, misses=0, maxsize=2, currsize=0)Gotchas
- Arguments must be hashable. The arguments become dictionary keys, so lists, dicts and sets raise
TypeError. Convert them first, for example to a tuple. - Only pure functions are safe. If the result depends on a file, the clock, or global state, the cache returns stale answers.
- Mutable results are shared. A cache hit returns the same object each time. If the function returns a list and a caller modifies it, every later caller sees the change.
- Argument style matters.
f(5)andf(n=5)are stored as separate entries.
import functools
@functools.lru_cache(maxsize=None)
def total(values):
return sum(values)
print(total((1, 2, 3))) # 6
try:
total([1, 2, 3])
except TypeError as error:
print(error) # unhashable type: 'list'property: methods that look like attributes
A property lets you run code on attribute access while callers keep using plain obj.name syntax. That lets you start with a simple attribute and add validation later without changing any calling code.
class Temperature:
def __init__(self, celsius):
self.celsius = celsius # goes through the setter below
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("below absolute zero")
self._celsius = value
@property
def fahrenheit(self):
return self._celsius * 9 / 5 + 32
t = Temperature(25)
print(t.fahrenheit) # 77.0
t.celsius = 30
try:
t.celsius = -300
except ValueError as error:
print(error) # below absolute zeroHow the setter decorator works
@property replaces the function with a property object. That object has .setter and .deleter methods. Each returns a new property that copies the old one and adds the new function. So this:
@celsius.setter
def celsius(self, value):
...is the same as celsius = celsius.setter(celsius_function). This is why the setter function must have the same name as the property. If you give it a different name, you create a second class attribute and the original property stays read-only.
Some points to remember:
- A property with no setter is read-only. Assigning to it raises
AttributeError. fahrenheitabove is computed on every access. If the computation is expensive,cached_propertystores the result after the first access.- The stored value lives under a different name (
_celsius). If the setter assigned toself.celsius, it would call itself forever.
staticmethod and classmethod
A normal method receives the instance as its first argument. These two decorators change that.
classmethodpasses the class itself as the first argument, conventionally namedcls.staticmethodpasses nothing extra. The function is an ordinary function that happens to live in the class namespace.
class Pizza:
def __init__(self, toppings):
self.toppings = toppings
@classmethod
def margherita(cls):
return cls(["mozzarella", "basil"])
@staticmethod
def is_valid_topping(name):
return name.isalpha()
class BigPizza(Pizza):
pass
print(type(BigPizza.margherita()).__name__) # BigPizza
print(Pizza.is_valid_topping("basil")) # Truemargherita is an alternative constructor. Because it uses cls instead of hard-coding Pizza, calling it on BigPizza builds a BigPizza. A staticmethod could not do that, since it has no access to the class. Use staticmethod for a helper that is related to the class but needs neither the class nor an instance. Often a module-level function is just as good.
Why these four are worth studying
Each one shows a different design from earlier chapters:
lru_cacheis a factory that returns a wrapper with extra attributes (cache_info,cache_clear), and it preserves the wrapped function's metadata asfunctools.wrapsdoes.property,staticmethodandclassmethodare classes, not functions. They work because instances of them are descriptors: objects whose special methods run when the attribute is looked up on a class or instance. A descriptor is how a function receivesselfautomatically, and these decorators change that behavior.
The descriptor detail explains a limit. These three only work inside a class body. A @property on a module-level function creates a property object that never gets called as one, so it does nothing useful.
Combining decorators with these
Stacking order matters, just as it does with your own decorators. The decorator closest to the function runs first, so classmethod and staticmethod usually go outermost, directly under any others in the stack. For example, @classmethod above @lru_cache caches by cls and the other arguments:
import functools
class Config:
@classmethod
@functools.lru_cache(maxsize=None)
def load(cls, name):
print(f"loading {name}")
return {"name": name}
Config.load("a")
Config.load("a") # no second "loading a" lineIf you reverse the order, lru_cache receives a classmethod object instead of a function, and the call fails. In Python 3.9 through 3.12 you could chain classmethod over property, but this was deprecated in 3.11 and removed in 3.13, so avoid it.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Passing a list to a cached function | `TypeError: unhashable type` | Pass a tuple or other hashable value |
| Caching an impure function | Stale results | Cache only functions of their arguments, or call `cache_clear()` |
| Setter named differently from the property | Property stays read-only | Reuse the exact name |
| Setter assigns to the property name | `RecursionError` | Store the value in `_name` |
| Omitting `cls` in a classmethod | `TypeError` about argument count | Add `cls` as the first parameter |
| `lru_cache` on a method of long-lived objects | Memory is never freed | Use `cached_property` or a per-instance cache |
Exercise
Write a class Circle that takes a radius in its constructor. Give it a radius property that raises ValueError if the value is negative, a read-only area property, and a classmethod named from_diameter that builds a circle from a diameter. Then explain why decorating area with lru_cache instead of using a plain property would be risky.
Show answer
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 non-negative") self.radius = value @property def area(self): return 3.141592653589793 * self.radius ** 2 @classmethod def fromdiameter(cls, diameter): return cls(diameter / 2) Because the constructor assigns through self.radius, the validation also runs at creation time. Using lrucache on area would put self in the cache key, so every Circle ever measured would stay in memory. Worse, if the radius changed later, the cache key (the same instance) would still match and return the old area. Computing area on each access, or using cached_property only for a value that never changes, avoids both problems.