02.04

Decorators and context managers

skillmaxingPython with AIDecorators and context managers
Visual lesson

Decorators and context managers

Included with Pro · 4:22
Lessons · 1,059 words

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.

Pro

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.

Unlock full access to
Python with AIAI researchComplete system design
30% off with LAUNCH30ends in 7h 40m
Buy now
View all plans ·Already Pro? Sign in
124 online