all Python 3contextlibterm
contextlib.closing
closing
Wraps an object so that its close() method is called automatically when the with block is left.
Syntax
contextlib.closing(thing)
It exists only for objects that have a close() method but do not implement the with protocol. Files, sockets and urlopen responses are already context managers in modern Python, so wrapping them adds nothing — closing is for third-party or legacy APIs. The close() call happens on both normal exit and exception, and an error raised by close() itself is not swallowed.
Examples
from contextlib import closing
# Сетевой пример — только для чтения, запускать в песочнице не нужно:
# from urllib.request import urlopen
# with closing(urlopen('http://example.com')) as page:
# data = page.read() # page.close() вызовется автоматически
class Res:
def close(self): print('closed')
with closing(Res()) as r:
pass # → closed
See also
Open in the full glossarydocs.python.orgReport an inaccuracy