__exit__Easy Examples

Called at the end of a with block; handles cleanup and exceptions

Implementing __exit__

Basic implementation of __exit__ in a class.

python
class FileManager:
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        print(f"Opening {self.name}")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(f"Closing {self.name}")
        if exc_type:
            print(f"  Error: {exc_val}")
        return False  # Don't suppress exceptions

with FileManager("data.txt"):
    print("Working with file")

__exit__ called at the end of a with block; handles cleanup and exceptions. Implementing it lets you customize how Python interacts with your objects.

__exit__ in action

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

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

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

d = Demo(42)
# This triggers __exit__:
print(d)

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

Want to try these examples interactively?

Open Easy Playground