Decorators and context managers
Decorators and context managers
Some behaviour belongs around code rather than inside it. Timing a call, logging that it happened, retrying it, opening a transaction before it and committing after. If you paste that behaviour into every function that needs it, you have twenty copies to keep in sync. Python has two tools for writing it once: a decorator, which wraps a function, and a context manager, which wraps a block of statements.
They are the same idea at two different grain sizes. A decorator says "every time this function is called, do this before and that after". A context manager says "for the statements inside this with block, do this before and that after, even if the block raises". Both are ordinary Python; there is no magic, only a convention about where the wrapping code goes.
Continue reading
Pro unlocks every video lesson, the full notes and runnable code across the Python with AI course, from the language itself to agents, MCP, Langfuse and deployment.