Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

object.__exit__

After successful entry the exit method closes the context and can determine whether an exception propagates.

Version: Python 3.14; repository image, production runtime not attested

Syntax

def __exit__(self, exc_type, exc_value, traceback): ...

After successful entry the exit method closes the context and can determine whether an exception propagates.

object.__exit__

On normal exit, including return, it receives three None values. On failure it receives the exception type, instance and traceback. A truthy result suppresses the exception and a falsey result lets it propagate.

Quiet suppresses ValueError, but KeyError reaches the outer except.

calls=[]
class C:
    def __enter__(self): return None
    def __exit__(self,*args):
        calls.append(args)
        return True
def f():
    with C(): return 9
assert f()==9 and calls==[(None,None,None)]

Examples

class Quiet:
    def __enter__(self): return self
    def __exit__(self, kind, error, trace):
        print(kind.__name__ if kind else "ok")
        return kind is ValueError

with Quiet(): pass
with Quiet(): raise ValueError("skip")
try:
    with Quiet(): raise KeyError("keep")
except KeyError:
    print("propagated")

Result

ok
ValueError
KeyError
propagated

Quiet suppresses ValueError, but KeyError reaches the outer except.

Sources