Skip to main content

Context Managers and Resource Handling

The with Statement

0:00
LearnStep 1/3

Mastering Resource Management

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:

python

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.

python

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:

python