0Pricing
Python Academy · Lesson

__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)  # 42

All lessons in this course

  1. The with Statement in Depth
  2. __enter__ and __exit__ Protocol
  3. contextlib: @contextmanager
  4. Practical Context Manager Patterns
← Back to Python Academy