🐍 Python Advanced

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

Why Interviewers Ask This

Interviewers ask this to evaluate whether you have the depth of knowledge needed to mentor others and lead technical decisions. The expected answer goes beyond definitions into practical implications and real-world consequences.

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.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Python answers easy to follow.