__enter__ and __exit__ Protocol
Build context managers using the dunder protocol.
The Context Manager Protocol
Any object that defines __enter__ and __exit__ is a context manager and can be used with with.
class Managed:
def __enter__(self):
print("entering")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("exiting")
return False
with Managed() as m:
print("inside")__enter__ Return Value
__enter__ is called at the start of the with block. Its return value is bound to the variable after as.
class Resource:
def __enter__(self):
self.value = 42
return self # bound to 'r'
def __exit__(self, *args):
self.value = None
return False
with Resource() as r:
print(r.value) # 42All lessons in this course
- The with Statement in Depth
- __enter__ and __exit__ Protocol
- contextlib: @contextmanager
- Practical Context Manager Patterns