Python · Concurrency & Runtime

__enter__() and __exit__()

Mediumenterexitcontext-managerdunder

Interview question

What do __enter__ and __exit__ do?

How to answer

The short answer

They implement the protocol used by with.

  • __enter__(self): runs on entry; its return value is bound to as target.
  • __exit__(self, exc_type, exc, tb): runs on exit.
  • Args are None if the body succeeded.
  • If an exception occurred, they describe it.
  • Return True to suppress the exception; any other falsy value lets it propagate.
Python
class ManagedResource:
    def __enter__(self):
        print("acquire")
        self.handle = {"ok": True}
        return self.handle

    def __exit__(self, exc_type, exc, tb):
        print("release")
        self.handle = None
        if exc_type is ValueError:
            print("suppressing ValueError")
            return True  # swallow
        return False     # propagate anything else

with ManagedResource() as h:
    print(h["ok"])
    # raise ValueError("boom")  # would be suppressed

Flow: __enter__ → body → __exit__ (always attempted), analogous to try/finally with optional exception handling.

Lock it in with a real drill

You remember an answer longer once you have used it. Try a hands-on problem on this concept.

Open related drill