all Python 3OOPfunction
__exit__
context manager
The method run on leaving a with block: always called, even on an exception, and given its type, value and traceback.
Syntax
def __exit__(self, exc_type, exc_value, traceback): ...
On a normal exit all three arguments are None. Returning a true value suppresses the exception and execution continues after the with; the default is to return None or False, otherwise errors vanish silently. __exit__ is what guarantees the file gets closed and the lock released.
Examples
class Guard:
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
print('exit:', exc_type.__name__ if exc_type else None)
return exc_type is ZeroDivisionError # подавить только деление на ноль
with Guard():
pass # → exit: None
with Guard():
1 / 0 # → exit: ZeroDivisionError
print('продолжаем') # → продолжаем — исключение подавлено
See also
Open in the full glossarydocs.python.orgReport an inaccuracy