Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / Python

Gestori di contesto

with lega il risultato di `__enter__` alla destinazione as e invoca `__exit__` all’uscita dal blocco.

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

Sintassi

with manager as resource:
    use(resource)

with lega il risultato di __enter__ alla destinazione as e invoca __exit__ all’uscita dal blocco.

Dopo un ingresso riuscito, l’uscita riceve normalmente tre None, oppure tipo, valore e traceback dell’eccezione. Un ritorno vero sopprime l’eccezione. Se fallisce l’ingresso, l’uscita del gestore non viene chiamata.

Stage restituisce ready e sopprime esattamente ValueError, permettendo di stampare continued.

calls=[]
class Context:
    def __init__(self,fail=False): self.fail=fail
    def __enter__(self):
        calls.append('enter')
        if self.fail: raise ValueError('entry')
        return self
    def __exit__(self,*exc): calls.append(exc[0]); return False
with Context(): pass
try:
    with Context(True): pass
except ValueError: pass
assert calls==['enter',None,'enter']

Esempi

class Stage:
    def __enter__(self):
        return "ready"

    def __exit__(self, kind, value, trace):
        print("exit", kind.__name__ if kind else "ok")
        return kind is ValueError

with Stage() as state:
    print(state)
    raise ValueError("skip")
print("continued")

Risultato

ready
exit ValueError
continued

Stage restituisce ready e sopprime esattamente ValueError, permettendo di stampare continued.

Fonti