Learn with diagrams, code, systems and practical examples.
Decorators and Context Managers
Wrap behavior and manage resource lifecycles with common Python patterns.
Decorators and context managers appear throughout web frameworks, testing tools, logging, files, locks, and transactions.
Start with the idea
A decorator receives a function and returns a wrapped function. A context manager defines setup and cleanup around a block used with the with statement.
Small working example
Run this example first. Do not change several things at once; confirm the basic behavior, then experiment.
from contextlib import contextmanager
@contextmanager
def section(name):
print("start", name)
yield
print("end", name)
with section("demo"):
print("work") A decorator receives a function and returns a wrapped function. A context manager defines setup and cleanup around a block used with the with statement.
- Decorators wrap callable behavior.
- Context managers manage setup and cleanup.
- Both should make lifecycle or cross-cutting behavior clearer.
start demo
work
end demoThe example is intentionally small. Focus on the chapter’s main idea before adding extra syntax or framework code.
Common beginner mistake
Using decorators for hidden side effects that make normal function behavior surprising.
Use wrappers when cross-cutting behavior is clear, documented, and easier than repeating it everywhere.
Quick recap
- Decorators wrap callable behavior.
- Context managers manage setup and cleanup.
- Both should make lifecycle or cross-cutting behavior clearer.
Try it yourself
These are deliberately small. If you can complete them without copying the example, you are ready to continue.
- Write a simple timing decorator.
- Create a context manager that prints before and after a block.