Implement Context Manager Methods
Core idea
A synchronous context manager implements enter(self) and exit(self, exc_type, exc_value, traceback). Entry prepares state and returns a value; exit receives exception information or three None values on normal departure. Return a false value to let exceptions propagate.
class Session: def __enter__(self): print("open") return "token" def __exit__(self, kind, value, tb): print("close", kind is None) return Falsewith Session() as token: print(token)Entry returns a string rather than the manager; exit receives no exception.
Restore state after an exception
class Flag: active = False def __enter__(self): self.active = True return self def __exit__(self, kind, value, tb): self.active = False print(kind.__name__ if kind else "ok") return Falseflag = Flag()try: with flag: raise RuntimeError("stop")except RuntimeError: print(flag.active)The exit method restores state before allowing the failure to propagate.
Common mistake
If enter fails after partially acquiring resources, it must clean up those acquisitions itself, for example using a try/finally or an internal ExitStack.
Practice
Build a manager that temporarily changes a flag, stores its original value, and restores it on normal and exceptional exit.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Context manager methods
Check your understanding of context manager methods.
What is printed?
class M: def __enter__(self): return 42 def __exit__(self,*args): return Falsewith M() as value: print(value)What is printed?
class M: def __enter__(self): return self def __exit__(self,*args): print(args==(None,None,None))with M(): passWhat must a partially failing __enter__ arrange?
What does a false exit result do when an exception is active?