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.
class Timer: def __enter__(self): return self def __exit__(self, exc_type, exc, tb): return False
Try it
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.
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
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 afterreturn,breakor 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_infoif you do not use the arguments:def __exit__(self, *exc_info). - Reentrancy. Storing per-use state on
self(likeself.old) breaks if the same instance is entered twice or nested. Create a new manager perwith, or document it. - Simpler to write: a generator with
@contextlib.contextmanager, where the code beforeyieldis__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 byasync with.
Related
- context managers,
with,contextlib,open() - Lessons: Context managers, Special methods