Skip to content
Open
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
6 changes: 5 additions & 1 deletion Lib/asyncio/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -601,7 +601,11 @@ async def __anext__(self):
raise StopAsyncIteration
assert self._todo_left > 0
self._todo_left -= 1
return await self._wait_for_one()
try:
return await self._wait_for_one()
except exceptions.CancelledError:
self._todo_left += 1
raise

def __next__(self):
if not self._todo_left:
Expand Down
20 changes: 20 additions & 0 deletions Lib/test/test_asyncio/test_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -1669,6 +1669,26 @@ async def coro(i):
)
self.assertCountEqual(results, (0, 1, 2, 3))

def test_as_completed_async_iterator_cancelled_anext(self):
async def main():
loop = asyncio.get_running_loop()
a = loop.create_future()
b = loop.create_future()
iterator = asyncio.as_completed([a, b])

waiter = asyncio.create_task(anext(iterator))
await asyncio.sleep(0)
waiter.cancel()
with self.assertRaises(asyncio.CancelledError):
await waiter

a.set_result('a')
b.set_result('b')
return [await f async for f in iterator]

results = self.loop.run_until_complete(main())
self.assertCountEqual(results, ['a', 'b'])

def test_as_completed_reverse_wait(self):
# Tests the plain iterator style of as_completed iteration to
# ensure that the first future awaited resolves to the first
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix :func:`asyncio.as_completed` to continue yielding every awaitable after
a pending asynchronous iteration step is cancelled.
Loading