Write reusable Python decorators

8 steps · about 2 h 45 min · Intermediate

  1. 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.

  2. 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.

  3. Practise the @ syntax on small examples (tutorial, Programiz, 15 min)

    Short runnable examples to confirm what @decorator expands to and how chaining orders calls.

  4. 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.

  5. Apply decorators to whole classes (reference, Python PEPs, 10 min)

    Shows class decorators as a lighter alternative to metaclasses for registering or modifying classes.

  6. 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.

  7. 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.

  8. Compare with a production decorator library (repo, GitHub, 15 min)

    wrapt shows the edge cases (methods, descriptors, introspection) a naive wrapper gets wrong.