On this page
contextlib.closing
Prev: contextlib.chdir | Up: contextlib | Next: contextlib.ContextDecorator
Rel: contextlib.AbstractAsyncContextManager, contextlib.AbstractContextManager, contextlib.aclosing, contextlib.asynccontextmanager
Ref: docs.python.org — contextlib.closing
Tags: #public #python3 #stdlib #contextlib
Import
import contextlib
from contextlib import closing
Signature & Overview
contextlib.closing(thing)
Context to automatically close something at the end of a block.
Usage
from contextlib import closing
class LegacyHandle:
def __init__(self) -> None:
self.closed = False
def close(self) -> None:
self.closed = True
h = LegacyHandle()
with closing(h) as active:
assert active is h
assert h.closed is True
Gotchas
- Bridges objects with
.close()but no__enter__/__exit__: Useful for legacy or third-party handles (like olderurllibor database cursors). - Not needed for modern files/sockets: Built-in
open()andsqlite3objects already work directly withwith.
REPL Inspect
from contextlib import closing
help(closing)
Linked from
Related notes
- tuts/python3/stdlib_module/contextlib/chdir Linked here; links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/ContextDecorator Linked here; links to this page; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextlib/AbstractAsyncContextManager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/AbstractContextManager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/aclosing Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/asynccontextmanager Linked here; shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/AsyncExitStack shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/contextmanager shared tags: #contextlib, #stdlib
- tuts/python3/stdlib_module/contextlib/ExitStack shared tags: #contextlib, #stdlib