They implement the context manager protocol used by with.
__enter__(self): runs on entry; its return value is bound toas target.__exit__(self, exc_type, exc, tb): runs on exit.- Args are
Noneif the body succeeded. - If an exception occurred, they describe it.
- Return
Trueto 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 suppressedFlow: __enter__ → body → __exit__ (always attempted), analogous to try/finally with optional exception handling.