7 routes42 sections324 units

Unit 3.5 · about 3 h

14 / 324

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.

  • implement

You can now

  • 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

Study, in this order

4 steps

  1. Decorators
    Stas' Python Cookbook - selected path

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

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

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

  3. Decorators
    AlgoMaster Python - structured revision

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

  4. functools Module
    AlgoMaster Python - structured revision

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

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.

Reproduce closed-book

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

Traps

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

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.

Self-test

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

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

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

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

Completion criterion

Stop when

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

Mark passed, then open 3.6 Only mark this when you can do it without notes.

Leads to

Comes after

Resources for this unit

  • Stas' Python Cookbook - selected path
    Stas Bekmanprimarycourse
    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 revision
    AlgoMastersupportpractice
    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 reference
    Python Software Foundationrequiredreference
    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 Projects
    Python Packaging Authorityrequiredimplementation
    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 classes
    Python Software Foundationreferencereference
    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 protocols
    Python Software Foundationreferencereference
    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 collector
    Python Software Foundationreferencereference
    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 references
    Python Software Foundationreferencereference
    Read weak-reference objects (ref callbacks, proxy objects) and the WeakValueDictionary example. Use for the weak-reference part of refcounting-gc-weakrefs.

Quick find

Search Michi

Type to search every route, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels