▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Decorators
Wrap functions to add timing, logging or caching.
🎬 Video version coming soon — read it now
A decorator wraps a function to add behaviour, such as timing, logging, caching or access checks, without changing the function's code. You've already used @dataclass and @property. Now you'll write your own.
Functions are objects
Functions can be stored, passed as arguments and returned from other functions. Decorators depend on this.
A decorator by hand
timer takes a function and returns a new function, wrapper, that does extra work around the original. *args, **kwargs pass any arguments straight through.
The @ syntax
@timer above the def means exactly slow_sum = timer(slow_sum). It's just neater.
Keep the function's identity: functools.wraps
Without @wraps, the decorated function's name and docstring become wrapper's, which confuses debugging and documentation tools. Always add it.
Decorators with arguments
One more layer: retry(times=5) returns the actual decorator.
Built-in decorators you'll use
@functools.lru_cache: remember results of expensive calls (in the Async & Performance course)@staticmethod,@classmethod: methods that don't need an instance@property,@dataclass: from Objects & Classes- Frameworks:
@app.get("/")in FastAPI,@pytest.fixturein testing
@something in a library, read it as "this function is being registered with, or wrapped by, something". That one sentence demystifies most framework code.In one line
A decorator takes a function and returns a wrapped version with extra behaviour; @name applies it, and functools.wraps keeps the original's identity.
Share with a friend