Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / Python

object.__exit__

Dopo un ingresso riuscito il metodo di uscita chiude il contesto e può decidere se l’eccezione si propaga.

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

Sintassi

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

Dopo un ingresso riuscito il metodo di uscita chiude il contesto e può decidere se l’eccezione si propaga.

object.__exit__

All’uscita normale, anche con return, riceve tre None, altrimenti tipo, istanza e traceback. Un ritorno vero sopprime l’eccezione, uno falso la lascia propagare.

Quiet sopprime ValueError, ma KeyError raggiunge l’except esterno.

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)]

Esempi

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")

Risultato

ok
ValueError
KeyError
propagated

Quiet sopprime ValueError, ma KeyError raggiunge l’except esterno.

Fonti