__enter__Easy Examples

Called at the start of a with block; returns the context resource

Implementing __enter__

Basic implementation of __enter__ in a class.

python
class Timer:
    def __enter__(self):
        import time
        self.start = time.time()
        print("Timer started")
        return self

    def __exit__(self, *args):
        import time
        elapsed = time.time() - self.start
        print(f"Elapsed: {elapsed:.4f}s")

with Timer():
    total = sum(range(1000000))
    print(f"Sum: {total}")

__enter__ called at the start of a with block; returns the context resource. Implementing it lets you customize how Python interacts with your objects.

__enter__ in action

Seeing __enter__ called by Python's built-in operations.

python
# How Python calls __enter__ automatically
class Demo:
    def __init__(self, value):
        self.value = value

    def __enter__(self):
        print(f"__enter__ was called!")
        return self

d = Demo(42)
# This triggers __enter__:
# with d: pass

Python automatically calls __enter__ when you use the corresponding operator or function on your object.

Want to try these examples interactively?

Open Easy Playground