Python Glossary Русский

Python 3.10+contextlibterm

contextlib.aclosing

managers

An async context manager ensuring aclose() is called on exit (3.10+).

Syntax

async with contextlib.aclosing(thing): ...

The main case is async generators with try/finally: if you leave an async for via break or an exception, the generator is not finalized right there — the event loop runs aclose() later as a separate task once the generator is collected (or in shutdown_asyncgens() for survivors), at an unpredictable moment and outside the iteration's context. aclosing makes the teardown happen deterministically where the block ends. It only works with objects exposing aclose(); for a plain sync close() use closing() instead.

Examples

# Python 3.11+
import contextlib
import asyncio
print(hasattr(contextlib.aclosing, '__call__'))   # → True
print(issubclass(contextlib.aclosing, contextlib.AbstractAsyncContextManager))   # → True
cm = contextlib.aclosing('resource')
print(hasattr(cm, '__aenter__') and hasattr(cm, '__aexit__'))   # → True
print(asyncio.run(cm.__aenter__()))   # → resource
with contextlib.aclosing(None): pass   # → TypeError

See also

Open in the full glossarydocs.python.orgReport an inaccuracy