Lesson 9: Decorators & Context Managers

⏱ ~35 min Lesson 9 of 14 💚 Free

Python has two elegant patterns that show up everywhere in professional code: decorators (which modify functions) and context managers (which manage resources). Understanding them unlocks most Python frameworks.

Key Concepts

Functions as Objects

In Python, functions are first-class objects — you can pass them to other functions, return them, store them in variables. This is the foundation of decorators.

Decorators

@timer
def slow_function(): ...
A decorator wraps a function to add behavior (logging, timing, caching, auth checks) without modifying the original code. @timer runs timer(slow_function) automatically.

Writing a Decorator

def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f'{func.__name__} took {time.time()-start:.3f}s')
return result
return wrapper

Context Managers

with open('file.txt') as f: is a context manager. It runs setup code on enter and cleanup code on exit — even if an error occurs. Write your own with __enter__ and __exit__ or @contextmanager.

✅ Check Your Understanding

1. In Python, a decorator is used to:

2. The with statement is used for:

3. @wraps(func) inside a decorator is used to: