Decorators and context managers
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))@timedaboveworkmeanswork = timed(work).functools.wrapskeeps the original name and docstring, which matters for debugging and tools.*args, **kwargslets 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.