CKTIS / Python
contextlib.closing
Omogoči with za vir s sinhrono metodo close().
Različica: Python 3.14; repository image, production runtime not attested
Sintaksa
with contextlib.closing(thing) as resource:Omogoči with za vir s sinhrono metodo close().
Vstop poda prvotni objekt, izhod pa pokliče close tudi po napaki v telesu. Izjema se navadno širi naprej, zato se closed pojavi pred handled.
Za asinhroni aclose je namenjen aclosing.
from contextlib import closing
seen = []
class Device:
def close(self):
seen.append("close")
d = Device()
try:
with closing(d) as value:
assert value is d
raise LookupError
except LookupError:
assert seen == ["close"]
Primeri
import contextlib
class Resource:
def close(self): print("closed")
try:
with contextlib.closing(Resource()):
raise ValueError
except ValueError:
print("handled")
Rezultat
closed handled
Za asinhroni aclose je namenjen aclosing.