CKTIS / Python
Parola chiave with
Entra nel contesto e lega facoltativamente il risultato di `__enter__` al bersaglio di as.
Versione: Python 3.14; repository image, production runtime not attested
Sintassi
with manager as value:
...Entra nel contesto e lega facoltativamente il risultato di __enter__ al bersaglio di as.
Dopo l’ingresso riuscito, __exit__ viene chiamato all’uscita dal blocco anche in caso di eccezione. Un risultato vero di __exit__ sopprime l’eccezione e uno falso la lascia propagare. Se fallisce lo stesso __enter__, Python non chiama __exit__ di quel gestore. Con più gestori si entra da sinistra a destra e si esce in ordine inverso.
Se un ingresso successivo fallisce, l’ultimo gestore entrato riceve l’eccezione e può sopprimerla.
Esempi
class Gate:
def __enter__(self):
return "inside"
def __exit__(self, typ, val, tb):
print(typ.__name__ if typ else "normal")
return typ is ValueError
with Gate() as label:
print(label)
raise ValueError("handled")
print("continued")
from contextlib import contextmanager
trace = []
@contextmanager
def record(name, fail=False):
trace.append("enter " + name)
if fail:
raise KeyError(name)
try:
yield
finally:
trace.append("exit " + name)
try:
with record("A"), record("B"), record("C", True):
raise AssertionError("body")
except KeyError:
pass
assert trace == ["enter A", "enter B", "enter C", "exit B", "exit A"]
Risultato
inside ValueError continued
Se un ingresso successivo fallisce, l’ultimo gestore entrato riceve l’eccezione e può sopprimerla.