In idiomatic Python, managing resources like files, network connections, or database locks is crucial. The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks.
The Old Way: try...finally
Before context managers, resources were often managed like this:
This is verbose and easy to get wrong. If you forget the finally block, an error could leave the file handle open.
The Idiomatic Way: with
The with statement ensures that the __exit__ method is called at the end of the nested block, even if an exception occurs.
How it Works
The protocol consists of two methods:
__enter__(self): Executed before the block. Return value is bound to the as variable.__exit__(self, exc_type, exc_val, exc_tb): Executed after the block. Handles cleanup.
Multiple Resources
You can handle multiple resources in a single line, which keeps nesting flat: