CKTIS / Python
contextlib.closing
Ermöglicht with für Ressourcen mit synchronem close().
Version: Python 3.14; repository image, production runtime not attested
Syntax
with contextlib.closing(thing) as resource:Ermöglicht with für Ressourcen mit synchronem close().
Beim Eintritt steht das ursprüngliche Objekt bereit, beim Austritt wird close auch nach einem Fehler im Rumpf aufgerufen. Die Ausnahme läuft normalerweise weiter, daher erscheint closed vor handled.
Für asynchrones aclose dient 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"]
Beispiele
import contextlib
class Resource:
def close(self): print("closed")
try:
with contextlib.closing(Resource()):
raise ValueError
except ValueError:
print("handled")
Ergebnis
closed handled
Für asynchrones aclose dient aclosing.