Context Managers
A context manager is an object that performs:- Setup before a block of code executes.
- Cleanup after the block finishes, even if an exception occurs.
with statement.
- Files
- Database connections
- Locks
- Network sockets
- Temporary directories
The Most Common Context Manager
Most Python developers use a context manager without realizing it.Step 1
Step 2
The returned object is assigned to the variable afteras.
file holds the object returned by open().
Step 3
The code inside the block executes.Step 4
When execution leaves thewith block, Python automatically closes the file.
How Does with Work?
Any object used with the with statement must implement two special methods.
__enter__()performs setup.__exit__()performs cleanup.
Creating a Context Manager Using a Class
as receives the value returned by __enter__().
Generator-Based Context Managers
Writing a class for simple setup and cleanup is often unnecessary. Python provides the@contextmanager decorator.
Understanding yield
The yield divides the function into two parts.
Before yield
with block.
The yielded value
as.
with block finishes, execution resumes after the yield.
Normal Execution
Example:yield.
Exception Handling
Now consider this example.Catching the Exception Inside the Generator
The generator itself can handle the exception.yield.
Complete Example
The following example demonstrates how an exception raised inside thewith block travels back into the generator.
Step 1
Python creates the generator.Step 2
Python enters the context.Step 3
Thewith block executes.
finally executes.
Step 4
Since an exception escaped from thewith block, Python does not call:
yield.
Conceptually,
Step 5
The generator catches the exception.yield.
Step 6
Finally always executes.FastAPI Uses the Same Mechanism
FastAPI uses generator-based context managers for dependencies.Key Takeaways
- A context manager automatically performs setup and cleanup.
- The
withstatement works with objects implementing__enter__()and__exit__(). - The variable after
asreceives the object returned by__enter__()or yielded by the generator. @contextmanagerprovides a concise way to create custom context managers.- Normal completion resumes the generator using
next(generator). - Exceptions resume the generator using
generator.throw(exception). generator.throw()injects the exception at the suspendedyield.- Statements after
yieldexecute only during normal execution. finallyalways executes, making context managers ideal for resource management.- FastAPI’s
yielddependencies are built on the same mechanism.