Skip to content
Visual explainer 3h to learn 4 steps

Decorators & context managers

Read and write simple decorators and custom with-blocks.

By Invicly Tech, , in Python Programming from Zero. About 10 minutes to read.

Topic 23 of 34

In short

A decorator is a function that wraps another function to add behaviour, like timing or logging, without changing its code. A context manager wraps a block with setup and cleanup, which is what with-statements use.

Explained simply

Sometimes you want extra behaviour around many functions: time them, log their calls, retry them if the network fails. Copying that code into every function is messy. A decorator lets you write the extra behaviour once and attach it with one line, @name, above any function.

This works because in Python a function is a normal object. You can pass it to another function and get a new function back. A decorator is exactly that: a function that takes your function, wraps it in a new one that adds the extra steps, and returns the wrapper.

A context manager does a similar job for a block of code instead of a function. The with statement runs setup before the block and cleanup after it, even if the block crashes. open() is the famous example: the file is always closed, whatever happens inside the with block.

You use both every day already: @property, @dataclass and with open(...) are all examples. Learning to write simple ones yourself lets you remove repeated setup and cleanup code from your projects.

Press Play on a diagram to walk through it one step at a time.

LayersA decorated call, outside in
  1. 1
    Caller

    Calls slow_sum(10), unaware of the wrapper

  2. 2
    wrapper()

    Starts timer, then calls the original

  3. 3
    Original slow_sum

    Does the real work and returns

  4. 4
    wrapper() again

    Stops timer, prints time, passes result back

FlowInside a with-block
  1. Step 1
    __enter__

    Setup: open, lock, start timer

  2. Step 2
    Run the body

    Your indented code

  3. Step 3
    __exit__

    Cleanup runs even if the body raised

LayersThree-level decorator with arguments: @retry(times=3)
  1. 1
    retry(times=3)

    Runs at import; stores the settings

  2. 2
    decorator(func)

    Runs at import; receives the function

  3. 3
    wrapper(...)

    Runs on every call; loops and retries

  4. 4
    func(...)

    Your original function, same arguments

In depth

Definition time vs call time

A decorator runs once, when Python reaches the def statement, which for module-level functions means when the module is imported. Writing @timer above def slow_sum is the same as defining slow_sum and then running slow_sum = timer(slow_sum). From then on the name slow_sum points to the wrapper.

The wrapper is what runs on every call. It can still use func because of a closure: an inner function remembers the variables of the outer function that created it, even after the outer function has returned. Keep this split in mind. Code directly inside the decorator (outside the wrapper) runs only once, at import. Code inside the wrapper runs on every call.

FlowWhat @timer does when Python reads def slow_sum
  1. Step 1
    Create function

    A function object for slow_sum is built

  2. Step 2
    Call timer(func)

    The decorator runs once, now

  3. Step 3
    Build wrapper

    A closure that remembers func

  4. Step 4
    Rebind the name

    slow_sum now refers to wrapper

Why functools.wraps matters

Without help, the wrapper replaces the original's identity. slow_sum.__name__ becomes "wrapper", its docstring disappears, and help(slow_sum) shows the wrapper's generic signature instead of the real parameters. Logs, tracebacks, pytest output and debuggers all get confusing, especially when ten functions share one decorator.

@functools.wraps(func) on the wrapper copies __name__, __qualname__, __doc__, __module__ and the function's attribute dict onto the wrapper, and stores the original in wrapper.__wrapped__. Tools like inspect.signature follow __wrapped__, so help() shows the real parameters again. There is no good reason to leave it out, so make it a habit for every decorator you write.

  • Without wraps: slow_sum.__name__ == "wrapper"
  • With wraps: slow_sum.__name__ == "slow_sum"
  • slow_sum.__wrapped__ gives back the undecorated function

Decorators with arguments, and stacking

@retry(times=3) has an extra layer. Python first calls retry(times=3), which must return the real decorator, which then receives the function and returns the wrapper. So a decorator with arguments is a function that returns a decorator: three nested functions.

You can stack decorators. With @a above @b above def f, Python applies the closest one first: f = a(b(f)). At call time the outer wrapper from a runs first and calls b's wrapper, which calls f. Order matters: put @functools.cache outside a logging decorator and cached calls are never logged. The standard library has useful ones: @functools.cache and @functools.lru_cache(maxsize=128) remember results, @property, @classmethod and @staticmethod change methods, and @dataclass changes a whole class.

  • @retry(times=3) means retry(times=3)(func)
  • @a @b def f means f = a(b(f))
  • @functools.cache needs hashable arguments

The context manager protocol

with EXPR as x: calls EXPR.__enter__() and binds its return value to x. When the block ends, Python calls __exit__(exc_type, exc_value, traceback). If the block finished normally, all three are None. If it raised, they describe the exception.

If __exit__ returns a true value, the exception is swallowed and the program continues after the with block. Returning None (the normal case) lets it propagate. Swallowing errors on purpose is rare; contextlib.suppress(FileNotFoundError) is the clear way to do it. You can open several managers in one statement: with open(a) as src, open(b, "w") as dst:. Other useful managers in the standard library: threading.Lock(), tempfile.TemporaryDirectory(), and contextlib.chdir(path) (Python 3.11+).

Sequencewith Timer() as t: body raises an error
with statement
Timer object
Your block
  1. 1__enter__()
    with statement to Timer object: __enter__()
  2. 2returns self, bound to t
    Timer object to with statement: returns self, bound to t
  3. 3run the block
    with statement to Your block: run the block
  4. 4raises ValueError
    Your block to with statement: raises ValueError
  5. 5__exit__(ValueError, err, tb)
    with statement to Timer object: __exit__(ValueError, err, tb)
  6. 6returns None: error propagates
    Timer object to with statement: returns None: error propagates

@contextmanager: rules for the generator

contextlib.contextmanager turns a generator function into a context manager. Code before yield is the setup. The yielded value is what as binds. Code after yield is the cleanup.

Two rules keep it correct. First, wrap the yield in try/finally. If the with block raises, the exception is thrown into your generator at the yield line, so cleanup written after a bare yield is skipped. Second, yield exactly once; yielding zero times raises RuntimeError: generator didn't yield, and twice raises generator didn't stop. If you need to manage a varying number of resources, for example opening every file in a list, use contextlib.ExitStack, which closes everything you registered in reverse order.

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Write a simple timing decorator~45m
  2. 2
    Use functools.wraps correctly~45m
  3. 3
    Write a context manager class~45m
  4. 4
    Use contextlib.contextmanager~45m

Key points

  • @timer above def f is shorthand for f = timer(f).
  • Wrappers should accept *args, **kwargs and return the original result.
  • Use functools.wraps so the wrapped function keeps its name and docstring.
  • @contextmanager turns a generator with one yield into a context manager.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
import functools, time

def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        print(f"{func.__name__} took {time.perf_counter() - start:.4f}s")
        return result
    return wrapper

@timer
def slow_sum(n):
    return sum(range(n))
print(slow_sum(1_000_000))  # prints the timing line, then 499999500000

A timing decorator; @contextmanager works similarly with a single yield.

A retry decorator with arguments

Network calls fail now and then. Step 1: retry(times, delay, exceptions) stores the settings and returns decorator. Step 2: decorator receives the function and returns wrapper, keeping the name with functools.wraps. Step 3: wrapper calls the function, catches only the listed exceptions, waits, and tries again. On the last attempt it re-raises with a bare raise, so the caller still sees the real error.

python
import functools, time

def retry(times=3, delay=0.5, exceptions=(Exception,)):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(1, times + 1):
                try:
                    return func(*args, **kwargs)
                except exceptions:
                    if attempt == times:
                        raise
                    time.sleep(delay)
        return wrapper
    return decorator

Temporarily setting an environment variable

Tests often need a setting changed for a short time and then restored. Step 1: remember the old value. Step 2: set the new one and yield. Step 3: in finally, put the old value back, or delete the variable if it did not exist. Because of try/finally, the environment is restored even if the code inside the with block fails.

python
import os
from contextlib import contextmanager

@contextmanager
def env_var(name, value):
    old = os.environ.get(name)
    os.environ[name] = value
    try:
        yield
    finally:
        if old is None: os.environ.pop(name, None)
        else: os.environ[name] = old

with env_var("APP_MODE", "test"):
    print(os.environ["APP_MODE"])   # test

Quick reference

  • @deco above def f is f = deco(f), run once at definition time
  • A wrapper takes *args and keyword args, passes all of them to func, and returns func's result
  • Always put @functools.wraps(func) on the wrapper
  • @a @b def f means f = a(b(f)); a's wrapper runs first at call time
  • @functools.cache memoises results for hashable arguments
  • __exit__ returning True swallows the exception; return None to let it propagate
  • In @contextmanager, wrap yield in try/finally and yield exactly once
  • contextlib.suppress(FileNotFoundError) ignores one error type on purpose

Common mistakes

  • Forgetting to return the result from the wrapper, so calls return None.
  • Leaving out @wraps, which breaks names in logs and tracebacks.
  • Not using try/finally around yield, so cleanup is skipped on errors.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A decorator prints "registering" outside its wrapper. When does that print?

Question 2

2Your wrapper calls the original function but has no return statement. What do decorated calls return?

Question 3

3With @log above @cache above def f, what happens on a repeated call with the same argument?

Question 4

4In a @contextmanager generator, cleanup code is written after a bare yield with no try/finally. The with block raises. What happens?

Question 5

5Which statement about functools.wraps is true?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a @log_calls decorator that prints the function name and its arguments before each call and returns the original result.

  2. Exercise 2medium

    Write a class-based context manager Timer that stores the elapsed seconds in t.elapsed, even when the block raises, and never hides the error.

  3. Exercise 3hard

    Write a context manager atomic_write(path) that gives you a file to write into, and only replaces path if the block succeeds. On an error, the old file must stay untouched.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Can a class be a decorator?
Yes. Anything callable that takes a function and returns a callable works. A class with __call__ can be a decorator, and decorators can also be applied to classes, like @dataclass.
What is the difference between functools.cache and lru_cache?
cache (Python 3.9+) keeps every result forever. lru_cache(maxsize=128) keeps only the most recently used results, which caps memory.
When should I write a context manager instead of try/finally?
When the same setup and cleanup appear in more than one place. A context manager puts that pair in one reusable, well-named object.
Do decorators slow my code down?
Each call goes through one extra function call, which costs well under a microsecond. That only matters inside very hot loops.

Go deeper

ShareXLinkedInWhatsApp