CKTIS / Python
contextlib.ExitStack
Gestisce un numero variabile di risorse scelte in esecuzione.
Versione: Python 3.14; repository image, production runtime not attested
Sintassi
with contextlib.ExitStack() as stack:Gestisce un numero variabile di risorse scelte in esecuzione.
callback non sopprime eccezioni, mentre una funzione registrata con push riceve i dati dell’eccezione e può sopprimerla con un risultato vero. enter_context entra in un gestore e ne registra l’uscita, callback registra una funzione senza dati di eccezione. Uscita o close esegue le azioni in ordine inverso. pop_all le trasferisce senza eseguirle.
Qui a work seguono second e first.
from contextlib import ExitStack
seen = []
with ExitStack() as original:
original.callback(seen.append, 1)
original.callback(seen.append, 2)
owned = original.pop_all()
assert not seen
owned.close()
assert seen == [2, 1]
with ExitStack() as s:
s.push(lambda typ, exc, tb: typ is KeyError)
raise KeyError("handled")
contextlib.ExitStack.enter_context · contextlib.ExitStack.close
enter_context(cm) chiama __enter__, registra l’uscita dopo un ingresso riuscito e restituisce il valore d’ingresso. close() svuota la pila in ordine inverso come per un’uscita normale senza eccezione. Chiudere la pila vuota non esegue nulla.
from contextlib import ExitStack
events=[]
class Lease:
def __init__(self, name): self.name=name
def __enter__(self): return self.name.upper()
def __exit__(self,*exc): events.append((self.name,exc[0]))
stack=ExitStack()
assert stack.enter_context(Lease('a'))=='A'
assert stack.enter_context(Lease('b'))=='B'
stack.close()
stack.close()
assert events==[('b',None),('a',None)]
Esempi
import contextlib
with contextlib.ExitStack() as stack:
stack.callback(print, "first")
stack.callback(print, "second")
print("work")
Risultato
work second first
Qui a work seguono second e first.