Skip to content

Core Python·Lesson 18 of 67·intermediate

Decorators and context managers

Wrap a function without touching it, build decorators that take arguments, and write your own with-blocks so setup and cleanup always pair up.


In this lesson · 20 min

  • →Explain closures, and how a decorator is built from one
  • →Write decorators that preserve the wrapped function's identity
  • →Build decorators that take arguments
  • →Cache expensive calls with functools.cache
  • →Write context managers as classes and with @contextmanager

Decorators and context managers solve the same problem from two directions: code that has to run around something else. Retries, timing, caching and logging around a function; setup and cleanup around a block.

Closures

A function defined inside another function remembers the variables it was created with, even after the outer call has returned:

PythonPython not started

That is all a decorator is: a function that takes a function and returns a replacement.

A first decorator

PythonPython not started

@announced above a def means exactly that reassignment:

PythonPython not started

*args, **kwargs in the wrapper is what makes a decorator work on any function, whatever its signature.

Keep the function’s identity

Replacing a function loses its name and docstring, which breaks documentation tools, tracebacks and anything that inspects the signature. functools.wraps copies them across:

PythonPython not started

Decorators that take arguments

A decorator with arguments is a function that returns a decorator — one more layer:

PythonPython not started

Read it outside-in: retry(attempts=4) runs first and returns decorator, which is then applied to flaky_call.

Stacking

Decorators apply bottom-up — the one nearest the def wraps first:

PythonPython not started

Caching

functools.cache remembers what a function returned for a given set of arguments. For anything pure and expensive — an embedding, a tokenisation, a parsed config — it is a one-line win:

PythonPython not started

functools.lru_cache(maxsize=1024) is the bounded version — use it when the set of inputs is unbounded, so the cache cannot grow forever.

Context managers

A with block guarantees that cleanup runs, whatever happens inside. Implementing __enter__ and __exit__ makes your own object work that way:

PythonPython not started

__exit__ receives the exception if one was raised. Returning False lets it propagate; returning True suppresses it — which you almost never want.

@contextmanager

For most cases, a generator is less ceremony. Everything before yield is setup, everything after is cleanup, and try/finally is what makes the cleanup unconditional:

PythonPython not started

contextlib has ready-made ones worth knowing:

PythonPython not started

Try it yourself

Exercise 1

Write the decorator logged(function): it appends call NAME to CALLS before running, returns the result unchanged, and preserves the wrapped function's name and docstring.

Your turnPython not started
Exercise 2

Write the context manager stage(name) with @contextmanager. It appends start NAME on entry and end NAME on exit — even when the block raises — and yields the name.

Your turnPython not started

Check yourself

What does @functools.wraps(function) do to the wrapper?

Check yourself

In a @contextmanager generator, why must the yield be inside a try/finally?

Recap

  • A closure is an inner function that remembers the names it was created with; a decorator is a function that takes a function and returns its replacement.
  • @decorator above a def is just f = decorator(f).
  • Accept *args, **kwargs in the wrapper, and always apply @functools.wraps.
  • A decorator with arguments is one extra layer: a function returning a decorator.
  • Stacked decorators apply bottom-up.
  • functools.cache memoises a pure function with hashable arguments; lru_cache(maxsize=...) bounds it.
  • with needs __enter__/__exit__, or a @contextmanager generator whose yield sits inside a try/finally.