Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Classes and Special Methods

__enter__() and __exit__()

Reference for Python __enter__() and __exit__(): implement context managers, the three exception arguments, suppressing errors and reusable managers.

These two methods make a class usable in a with statement. __enter__() runs as the block starts and supplies the value after as. __exit__() runs when the block ends, however it ends, and receives details of any exception.

Use them to guarantee cleanup: release a lock, roll back a transaction, restore a setting, or close a resource.

Python
class Timer:
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc, tb):
        return False

Try it

Python Entering and exiting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Suppressing exceptions and restoring state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
class C:
    def __enter__(self):
        ...
        return value

    def __exit__(self, exc_type, exc_value, traceback):
        ...
        return True or False
Parameter of __exit__ Description
exc_type The exception class, or None if the block finished without an error.
exc_value The exception instance, or None.
traceback The traceback object, or None.

Return value: __enter__() returns the value bound by as (often self). __exit__() returns a true value to suppress the exception, false or None to let it continue.

Raises: TypeError or AttributeError when the object lacks the methods (the exact error depends on the Python version). An exception raised inside __exit__() replaces the original one.

Usage notes

  • __exit__ always runs once __enter__() has completed, even after return, break or an exception. If __enter__() itself raises, __exit__() is not called.
  • Do not re-raise the exception inside __exit__(). Return a false value and Python re-raises the original with its traceback intact.
  • Return true sparingly. Suppressing errors is almost always better done with contextlib.suppress, or limited to a precise exception type as above.
  • Accept *exc_info if you do not use the arguments: def __exit__(self, *exc_info).
  • Reentrancy. Storing per-use state on self (like self.old) breaks if the same instance is entered twice or nested. Create a new manager per with, or document it.
  • Simpler to write: a generator with @contextlib.contextmanager, where the code before yield is __enter__() and the code after is __exit__().
  • Several managers in one statement are entered left to right and exited right to left.
  • Async: __aenter__() and __aexit__() are used by async with.