diff options
Diffstat (limited to 'Lib/contextlib.py')
-rw-r--r-- | Lib/contextlib.py | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/Lib/contextlib.py b/Lib/contextlib.py index ff92d9f..82ddc14 100644 --- a/Lib/contextlib.py +++ b/Lib/contextlib.py @@ -303,6 +303,32 @@ class closing(AbstractContextManager): self.thing.close() +class aclosing(AbstractAsyncContextManager): + """Async context manager for safely finalizing an asynchronously cleaned-up + resource such as an async generator, calling its ``aclose()`` method. + + Code like this: + + async with aclosing(<module>.fetch(<arguments>)) as agen: + <block> + + is equivalent to this: + + agen = <module>.fetch(<arguments>) + try: + <block> + finally: + await agen.aclose() + + """ + def __init__(self, thing): + self.thing = thing + async def __aenter__(self): + return self.thing + async def __aexit__(self, *exc_info): + await self.thing.aclose() + + class _RedirectStream(AbstractContextManager): _stream = None |