appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Decorators and context managers

Lesson 2 of 512 minAdvanced

Wrap functions with extra behaviour and guarantee setup and cleanup.

Functions are objects. You can pass them around, return them and wrap them. A decorator is a function that takes a function and returns an improved one.

import functools, time

def timed(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        try:
            return fn(*args, **kwargs)
        finally:
            print(f"{fn.__name__} took {time.perf_counter() - start:.3f}s")
    return wrapper

@timed
def work(n):
    return sum(range(n))
  • @timed above work means work = timed(work).
  • functools.wraps keeps the original name and docstring, which matters for debugging and tools.
  • *args, **kwargs lets the wrapper accept any call.
  • The standard library has useful ones: functools.cache, functools.lru_cache, @staticmethod, @property.

Context managers

A context manager guarantees cleanup around a block with with. Write one with contextlib.

from contextlib import contextmanager
import os

@contextmanager
def working_dir(path):
    old = os.getcwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(old)

with working_dir("/tmp"):
    print(os.getcwd())

Code after yield runs when the block ends, even if it raised an exception. That is why with open(...) never leaks a file.

Carefulfunctools.cache stores every result forever. Never use it on a function with unbounded different arguments, or memory will grow without limit. lru_cache(maxsize=...) keeps only the most recent ones.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. What does @timed above def work mean?
2. Why use functools.wraps in a decorator?
3. When does the code after yield in a @contextmanager function run?

Key terms