Skip to content
LakeBench
ProblemsCommunityPricing
Sign inStart practicing
Back
  1. Home
  2. Interview prep
  3. __enter__() and __exit__()

Python · Concurrency & Runtime

__enter__() and __exit__()

Mediumpython-29
enterexitcontext-managerdunder

Question

What do __enter__ and __exit__ do?

Solution

They implement the context manager 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.
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.

🎯 Put this concept into practice

Solidify this answer with real hands-on interview drills in the browser studio.

Open related drill →
PreviousNext