🐍 Python Advanced

What is Python's __enter__ and __exit__ for custom context managers?

Answer

Implementing the context manager protocol via __enter__ and __exit__ gives full control over resource management. __enter__(self): called when entering the with block, returns the resource (or self). __exit__(self, exc_type, exc_val, exc_tb): called on exit, receives exception info (all None if no exception). Return True to suppress the exception; return False/None to propagate it. Example: class DatabaseConnection: def __enter__(self): self.conn = connect(); return self.conn; def __exit__(self, et, ev, tb): if et: self.conn.rollback(); else: self.conn.commit(); self.conn.close(); return False. Class-based CMs are useful when __init__ needs arguments or cleanup is complex. For simpler cases, use @contextmanager. Async context managers implement __aenter__ and __aexit__ (both coroutines) for use with async with.