Sub topic 3
Python Decorators: Wrapping Functions to Add Behavior
Assume you can define functions, pass positional and keyword arguments, write basic classes and methods, and import standard-library modules.
Standard-library decorators
Python already provides decorators for common patterns:
functools.lru_cacheremembers results. Its arguments must be hashable.propertymakes a method behave like a read-only attribute.staticmethodremoves automatic instance or class binding.classmethodpasses the class asclsinstead of an instance asself.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
class User:
def __init__(self, name):
self.name = name
@property
def label(self):
return self.name.upper()
@staticmethod
def valid_name(name):
return bool(name.strip())
@classmethod
def guest(cls):
return cls("Guest")
print(User.guest().label)A cached instance method also caches self as part of its key. This can keep instances alive longer than expected.
Class-based decorators
A class can act as a decorator when it defines __call__. This is useful when the decorator needs state.
import functools
class CountCalls:
def __init__(self, func):
functools.update_wrapper(self, func)
self.func = func
self.count = 0
def __call__(self, *args, **kwargs):
self.count += 1
return self.func(*args, **kwargs)
@CountCalls
def ping():
return "pong"Decorating classes
A class decorator receives the class object. It can register or modify that class.
REGISTRY = {}
def register(cls):
REGISTRY[cls.__name__] = cls
return cls
@register
class CsvExporter:
passAsync functions and typed decorators
An async wrapper must also be async and must await the wrapped call.
import functools
from typing import Callable, ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")
def logged(func: Callable[P, R]) -> Callable[P, R]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
print(func.__name__)
return func(*args, **kwargs)
return wrapperFor an async function, replace the wrapper with async def and return await func(...). ParamSpec preserves the wrapped function’s parameter types for type checkers.
Common pitfalls
- A decorator factory needs its call: use
@repeat(3), not@repeat. - Use
functools.wrapsor metadata such as__name__and docstrings is lost. - Forward both
*argsand**kwargs. - Check whether decorator order changes behavior.
> callout note > When debugging, temporarily remove @syntax, call the decorator explicitly, and inspect function.__name__ and function.__doc__.
Exercise
What does @logged above def add(a, b): ... do?
Show answer
It reassigns add to the wrapper returned by logged(add), so calls to add go through the wrapper.