Python Context Managers: Beyond the with Statement
The with statement is more than just file handling. Here is how I build custom context managers for resource management, locking, and cleanup. Context managers are the mechanism behind the with statement. Most developers encounter them first with file operations, where with open(. ) guarantees the file closes even if an exception occurs. That guarantee. setup, do work, cleanup. is the entire point. Once I understood that context managers are a protocol for guaranteed teardown, I started finding uses far beyond files. The Protocol: __enter__ and __exit__ A context manager is any object that implements __enter__ and __exit__ . The with statement calls __enter__ before the block runs and __exit__ after, regardless of whether an exception occurred. The return value of __enter__ is assigned to the variable after as . class DatabaseConnection: def __init__(self, dsn): self.dsn = dsn self.conn = None def __enter__(self): self.conn = connect(self.dsn) return self.conn def __exit__(self, exc_type, exc_val, exc_tb): self.conn.close() # Return False (or None) to propagate exceptions return False with DatabaseConnection(dsn) as conn: conn.execute('SELECT 1') The __exit__ method receives the exception type, value, and traceback if an exception occurred. If it returns True , the exception is suppressed.…