__exit__

Dunder MethodPython 2.0+Intermediate

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

Quick Info

Documentation
Official Docs
Python Version
2.0+

Learn by Difficulty

Quick Example

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.

Try in Playground

Tags

oopmagic-methodprotocolcore