CKTIS / Python
contextlib.closing
Adapts an object with a close method into a context manager that always closes it.
Version: Python 3.14; repository image, production runtime not attested
Syntax
with contextlib.closing(thing) as resource:Adapts an object with a close method into a context manager that always closes it.
The close call runs on scope exit even if the body raises before it reaches normal completion.
Wrap a resource that supplies close() but has no context-manager protocol. Entry hands back the original resource. Exit calls its synchronous close() even if the body failed and normally allows the body exception to propagate. In the example closed is printed before handled. An asynchronous aclose method needs aclosing instead.
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"]
Examples
import contextlib
class Resource:
def close(self): print("closed")
try:
with contextlib.closing(Resource()):
raise ValueError
except ValueError:
print("handled")
Result
closed handled
Wrap a resource that supplies close() but has no context-manager protocol. Entry hands back the original resource. Exit calls its synchronous close() even if the body failed and normally allows the body exception to propagate. In the example closed is printed before handled. An asynchronous aclose method needs aclosing instead.