Write reusable Python decorators
8 steps · about 2 h 45 min · Intermediate
- Start with inner functions and closures (tutorial, Real Python, 25 min)
Decorators are closures; this shows how an inner function keeps state from its enclosing scope.
- Build timing, debug and retry decorators step by step (tutorial, Real Python, 45 min)
Walks from a bare wrapper to decorators with arguments, functools.wraps and stateful classes.
- Practise the @ syntax on small examples (tutorial, Programiz, 15 min)
Short runnable examples to confirm what @decorator expands to and how chaining orders calls.
- Read why function decorators were added (reference, Python PEPs, 20 min)
The design record explains the evaluation order and the cases decorators were meant to replace.
- Apply decorators to whole classes (reference, Python PEPs, 10 min)
Shows class decorators as a lighter alternative to metaclasses for registering or modifying classes.
- Use any expression after the @ sign (reference, Python PEPs, 10 min)
Python 3.9 relaxed the grammar, so decorators can come from dict lookups or subscript expressions.
- Type-hint decorators with ParamSpec (reference, Python PEPs, 25 min)
ParamSpec lets mypy and IDEs see the wrapped function's real parameters instead of *args, **kwargs.
- Compare with a production decorator library (repo, GitHub, 15 min)
wrapt shows the edge cases (methods, descriptors, introspection) a naive wrapper gets wrong.