Unit 5 of 9 · about 3 hours · implement

Decorators, wrappers and parameterized decorators

Retry, timing, caching and registration later are all decorators. A wrapper that drops metadata corrupts help, test ids and error messages.

You'll be able to

  • Implement a behavior-preserving wrapper with functools.wraps and forwarded *args/**kwargs.
  • Implement a parameterized decorator factory with its own state, such as retry with a budget.
  • Predict metadata loss, double-application and unhashable-argument failures in wrappers.

Covers

Decorators, wrappers, metadata and parameterized decorators
1

Read

In this order, only the parts listed

0 of 4 done

  1. DecoratorsStas' Python Cookbook - selected path

    Functions: Decorators (the timed wrapper with functools.wraps); the no-op fallback pattern for optional dependencies

  2. functools: partial, caching, reduceStas' Python Cookbook - selected path

    functools: partial, lru_cache and cache bounds, reduce; cache keys need hashable arguments

  3. DecoratorsAlgoMaster Python - structured revision

    The Decorators lesson and Exercise: Decorators; write the wrapper from memory first

  4. functools ModuleAlgoMaster Python - structured revision

    The functools Module lesson: compare wraps, lru_cache and partial behavior after the cookbook pass

2

Focus on

  • A decorator replaces the function object. Without @wraps the name, docstring and signature come from the wrapper; with it, __wrapped__ points back.
  • A decorator with arguments is three levels: the factory call, then the decorator, then the wrapper. State which level each argument belongs to.
  • lru_cache and cache key on all arguments. Unhashable arguments raise TypeError; an unbounded cache grows one entry per distinct call.
  • Wrappers must forward *args and **kwargs untouched, including self for methods; returning the inner result keeps the return contract.
Common mistakes · 3
  • Forgetting @wraps on a wrapper. Test ids and help show wrapper and failures get harder to trace.
  • Writing @retry without the factory call. The function lands in the times parameter, the name is bound to the inner decorator, and the first call wraps its argument instead of running.
  • Caching a function of large or unhashable inputs. Memory grows silently or the first call raises TypeError.
3

Try it yourself

Closed-book, before checking anything

Closed-book, write retry(times) that preserves __name__ and reruns on ValueError, and show three attempts ending in success plus lru_cache raising TypeError on a list argument (both verified on CPython 3.14.4).
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.What breaks when @wraps is missing from a wrapper?Answer

    __name__, __doc__ and the signature come from the wrapper, and __wrapped__ is absent. Debuggers, help and pytest ids show wrapper.

  2. 2.Why does a cached function fail on f([1, 2])?Answer

    Cache keys need hashing and list is unhashable, so the call raises TypeError before the body runs.

  3. 3.Sketch the three levels of @retry(3) and what each receives.Answer

    retry(3) returns the decorator; the decorator receives the function; the wrapper receives the call arguments and loops.

  4. 4.A timed decorator swallows the return value. Which contract breaks, and what is the one-line fix?Answer

    Callers get None instead of the result. Return fn(*args, **kwargs) from the wrapper, through try/finally for timing.

5

Practice

  • AlgoMaster Python: Exercise: Decorators

    Exercises 1 to 5, especially Exercise 2: Preserve Metadata with wraps, Exercise 4: Trace Stacked Decorators and Exercise 5: Retry a Failing Function

    Implement the retry factory in your own file first, then add an lru_cache variant of one answer and state its key policy.

You're done when

Your retry wrapper preserves metadata, retries the seeded failure, and you can name the cache key policy for any wrapper.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 6 more in the section
  • Stas' Python Cookbook - selected pathStas Bekman · primary

    Run Part I on dictionaries, iteration, functions, closures, decorators, classes and context managers; Part II on modules, files, paths, environment and arguments; and Part IV on versions, dependencies, packaging and code quality. Finish by building one src-layout package from a blank directory.

  • AlgoMaster Python - structured revisionAlgoMaster · support

    Use Functions, Modules and Packages, OOP, Advanced OOP, Exception Handling, Iterators and Generators, Type Hints and Annotations only after the cookbook pass. Open it for recall practice or a diagnosed weak mechanism, not as a second complete course.

Also in this section

  • Python language referencePython Software Foundation · required

    Check Data model, Execution model, Import system and Exceptions whenever a claim depends on Python semantics. These pages are the authority when the course and a runtime observation disagree.

  • Packaging Python ProjectsPython Packaging Authority · required

    Follow the packaging tutorial once from a blank directory, using a src layout, pyproject.toml, an isolated build and a clean-environment installation test.

  • dataclasses - data classesPython Software Foundation · reference

    Read the @dataclass parameters (eq, order, frozen, slots), field() with default_factory, frozen instances, post-init processing, replace, asdict and astuple. Use for the validated frozen dataclass in attributes-protocols-dataclasses.

  • typing - type hints and protocolsPython Software Foundation · reference

    Read Protocols for structural typing and runtime_checkable limits, Generics for TypeVar generics, and assert_type for narrowing checks. Use for the Protocol and narrowing parts of type-hints-protocols; PEP 695 syntax itself is in the language reference.

  • gc - cycle garbage collectorPython Software Foundation · reference

    Read the cycle collector interface: collect, get_count, garbage and disable/enable. Use for the cycle-collection and measurement parts of refcounting-gc-weakrefs.

  • weakref - weak referencesPython Software Foundation · reference

    Read weak-reference objects (ref callbacks, proxy objects) and the WeakValueDictionary example. Use for the weak-reference part of refcounting-gc-weakrefs.