Skip to content

bpo-40213: add contextlib.aclosing() #22640

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions Doc/library/contextlib.rst
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,39 @@ Functions and classes provided:
``page.close()`` will be called when the :keyword:`with` block is exited.


.. function:: aclosing(thing)

Return an async context manager that closes *thing* upon completion of the
block. This is basically equivalent to::

from contextlib import asynccontextmanager

@asynccontextmanager
async def aclosing(thing):
try:
yield thing
finally:
await thing.aclose()

Significantly, ``aclosing()`` supports deterministic cleanup of async
generators when they happen to exit early by :keyword:`break` or an
exception. For example::

from contextlib import aclosing

async with aclosing(my_generator()) as values:
async for value in values:
if value == 42:
break

This pattern ensures that the generator's async exit code is executed in
the same context as its iterations (so that exceptions and context
variables work as expected, and the exit code isn't run after the
lifetime of some task it depends on).

.. versionadded:: 3.10


.. _simplifying-support-for-single-optional-context-managers:

.. function:: nullcontext(enter_result=None)
Expand Down
43 changes: 42 additions & 1 deletion Lib/contextlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
__all__ = ["asynccontextmanager", "contextmanager", "closing", "nullcontext",
"AbstractContextManager", "AbstractAsyncContextManager",
"AsyncExitStack", "ContextDecorator", "ExitStack",
"redirect_stdout", "redirect_stderr", "suppress"]
"redirect_stdout", "redirect_stderr", "suppress", "aclosing"]


class AbstractContextManager(abc.ABC):
Expand Down Expand Up @@ -303,6 +303,47 @@ def __exit__(self, *exc_info):
self.thing.close()


class aclosing(AbstractAsyncContextManager):
"""Async context to automatically close something at the end of a block.

Code like this:

async with aclosing(<module>.open(<arguments>)) as f:
<block>

is equivalent to this:

f = await <module>.open(<arguments>)
try:
<block>
finally:
await f.aclose()

This is especially useful to ensure that an async generator that has exited
early due to `break` or exception will run its async exit code in the same
context as its iterations (so that exceptions and context variables work as
expected, and the exit code isn't run after the lifetime of some task it
depends on). Instead of this:

async for value in my_generator():
if value == 42:
break

do this:

async with aclosing(my_generator()) as values:
async for value in values:
if value == 42:
break
"""
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
Expand Down
62 changes: 61 additions & 1 deletion Lib/test/test_contextlib_async.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import asyncio
from contextlib import asynccontextmanager, AbstractAsyncContextManager, AsyncExitStack
from contextlib import asynccontextmanager, AbstractAsyncContextManager, AsyncExitStack, aclosing
import functools
from test import support
import unittest
Expand Down Expand Up @@ -453,5 +453,65 @@ async def suppress_exc(*exc_details):
self.assertIsInstance(inner_exc.__context__, ZeroDivisionError)


class AsyncClosingTestCase(unittest.TestCase):

@_async_test
async def test_aclosing(self):
state = []
class C:
async def aclose(self):
state.append(1)
x = C()
self.assertEqual(state, [])
async with aclosing(x) as y:
self.assertEqual(x, y)
self.assertEqual(state, [1])

@_async_test
async def test_aclosing_error(self):
state = []
class C:
async def aclose(self):
state.append(1)
x = C()
self.assertEqual(state, [])
with self.assertRaises(ZeroDivisionError):
async with aclosing(x) as y:
self.assertEqual(x, y)
1 / 0
self.assertEqual(state, [1])

@staticmethod
async def _async_range(count, closed_slot):
try:
for i in range(count):
yield i
except GeneratorExit:
closed_slot[0] = True

@_async_test
async def test_generator_example(self):
closed_slot = [False]
async with aclosing(self._async_range(10, closed_slot)) as gen:
it = iter(range(10))
async for item in gen:
assert item == next(it)
if item == 4:
break
assert closed_slot[0]

@_async_test
async def test_generator_example_error(self):
closed_slot = [False]
with self.assertRaises(ValueError):
async with aclosing(self._async_range(10, closed_slot)) as gen:
it = iter(range(10))
async for item in gen:
assert item == next(it)
if item == 4:
raise ValueError()
assert closed_slot[0]


if __name__ == '__main__':
unittest.main()
1 change: 1 addition & 0 deletions Misc/ACKS
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ Stefan Behnel
Reimer Behrends
Ben Bell
Thomas Bellman
John Belmonte
Alexander “Саша” Belopolsky
Eli Bendersky
Nikhil Benesch
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Added contextlib.aclosing(), async equivalent to the closing() context
manager. Especially useful for deterministic cleanup of async generators.