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.
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.
- 1Caller
Calls slow_sum(10), unaware of the wrapper
- 2wrapper()
Starts timer, then calls the original
- 3Original slow_sum
Does the real work and returns
- 4wrapper() again
Stops timer, prints time, passes result back
- Step 1__enter__
Setup: open, lock, start timer
- Step 2Run the body
Your indented code
- Step 3__exit__
Cleanup runs even if the body raised
- 1retry(times=3)
Runs at import; stores the settings
- 2decorator(func)
Runs at import; receives the function
- 3wrapper(...)
Runs on every call; loops and retries
- 4func(...)
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.
- Step 1Create function
A function object for slow_sum is built
- Step 2Call timer(func)
The decorator runs once, now
- Step 3Build wrapper
A closure that remembers func
- Step 4Rebind 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+).
- with statement to Timer object: __enter__()1__enter__()
- Timer object to with statement: returns self, bound to t2returns self, bound to t
- with statement to Your block: run the block3run the block
- Your block to with statement: raises ValueError4raises ValueError
- with statement to Timer object: __exit__(ValueError, err, tb)5__exit__(ValueError, err, tb)
- Timer object to with statement: returns None: error propagates6returns 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.
- 1Write a simple timing decorator~45m
- 2Use functools.wraps correctly~45m
- 3Write a context manager class~45m
- 4Use 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
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 499999500000A 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.
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 decoratorTemporarily 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.
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"]) # testQuick 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.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a @log_calls decorator that prints the function name and its arguments before each call and returns the original result.
- 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.
- 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.