Writing a context manager: __enter__ and __exit__
🌍 In real life. At a hotel, check-in gives you a room key, and check-out takes it back and tidies the room, whether your stay went well or the shower broke.
Any class can work with with if it has two dunder methods:
__enter__(self)is check-in: it runs on the way in, and whatever it returns is whatasnames__exit__(self, exc_type, exc, tb)is check-out: it runs on the way out, always
Such an object is called a context manager. Watch the flow come in through the __enter__ door and leave through the __exit__ door:
The idea in one sentence: any class becomes a context manager by having __enter__ (runs on the way in; its return value goes after as) and __exit__ (runs on the way out, always).
Its words:
__enter__(self): setup; return the thing the block will use__exit__(self, exc_type, exc, tb): clean-up, told about any error- swallowing an error:
__exit__returning True stops the error from going any further
class Hotel:
def __enter__(self):
print("checked in")
return "key 101"
def __exit__(self, exc_type, exc, tb):
print("checked out")
with Hotel() as key:
print("using", key)
print("taxi home")What __exit__ is told, step by step. Its three extra parameters describe any error that happened in the block:
- no error: all three are
None - an error:
exc_typeis its class (likeValueError) andexcis the error itself - if
__exit__returns True, the error is swallowed and the program carries on after the block; otherwise (returning nothing) the error keeps going
Swallowing errors hides problems, so only do it for an error you truly expect, like a hotel that shrugs off a lost towel but not a fire.
class ShrugOff:
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
if exc_type is ValueError:
print("ignored:", exc)
return True # swallow only ValueError
return False
with ShrugOff():
int("not a number")
print("still running")Why a class? When the setup and clean-up need to remember things (a start time, a counter, a connection), a class keeps that state in its attributes between __enter__ and __exit__.
Mistakes and edge cases.
- Forgetting to return self from enter. Then
as namegetsNone. - Returning True from exit by accident. It hides every error in the block; return nothing (None) unless you really mean to swallow it.
- Too few parameters on exit. Python always passes three error details;
def __exit__(self):fails when the block ends.
Quiz
What does this print?
class Door: def __enter__(self): print("open") return "inside" def __exit__(self, exc_type, exc, tb): print("shut") with Door() as where: print(where)What does this print?
class Guard: def __enter__(self): return self def __exit__(self, exc_type, exc, tb): print("exit sees", exc_type) with Guard(): print("fine")What happens if
__exit__returns True after an error in the block?- The error is swallowed and the program carries on after the block
- The block runs again
- The error is printed twice
What does this print?
class Hotel: def __enter__(self): print("in") def __exit__(self, exc_type, exc, tb): print("out") try: with Hotel(): raise ValueError("broken shower") except ValueError as e: print("complaint:", e)Which line has a mistake?
class Hotel: def __enter__(self): return "key" def __exit__(self): print("checked out") with Hotel() as key: print(key)
Coding tasks
Write a class
Announcethat works withwith: on the way in it prints"begin", on the way out it prints"end".Write a class
Hotelwhose__enter__returns"room 101", and whose__exit__setsself.checked_out = True. (stay()is written for you; don't change it.)Write a class
Quietwhose__exit__swallows a ValueError (returns True) but lets every other error carry on. (attempt()anddivide()are written for you.)