Skip to main content

Context Managers and Resource Handling

Writing Context Managers with Classes

0:00
LearnStep 1/3

The Context Management Protocol

While Python provides many built-in context managers, creating your own allows you to encapsulate custom setup and teardown logic. This is done by implementing the Context Management Protocol in a class.

The Protocol Methods

  • __enter__(self): Executed when the with block begins. If an as clause is used, the value returned by this method is assigned to the target variable.
  • __exit__(self, exc_type, exc_val, exc_tb): Executed when the block finishes. It receives three arguments if an exception occurred; otherwise, all are None.

Exception Handling in __exit__

The __exit__ method can control how exceptions are handled. If it returns True, the exception is suppressed. If it returns False (or None), the exception propagates normally.

python

When to Use Class-Based Managers

Classes are ideal when the context manager needs to maintain state or when you want to provide additional methods (like query() above) to be used within the with block.