Special Method Protocols

__exit__() — context protocol

Leave a synchronous context manager. Receives three None values on normal exit, otherwise exception information. A truthy return suppresses the exception; false leaves it propagating. Perform cleanup regardless of the path.

Formal Syntax & Structure

python syntaxpython
def __exit__(self, exc_type, exc_value, traceback):

Parameters & Attributes

NameTypeDescription
exc_typetype | NoneException class.
exc_valueBaseException | NoneException instance.
tracebacktraceback | NoneTraceback.

Return Value

object

Truth-tested suppression decision.

Working Example

Example Snippetpython
class IgnoreMissing:    def __enter__(self): return self    def __exit__(self, exc_type, exc_value, traceback): return exc_type is KeyErrordef demo():    with IgnoreMissing(): raise KeyError("missing")    return "continued"print(demo())
Python Reference