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
8 changes: 7 additions & 1 deletion Lib/asyncio/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -578,7 +578,13 @@ def __init__(self, aws, timeout):
self._timeout_handle = None

loop = events.get_event_loop()
self._cur_task = current_task()
# The iterator may be created outside of a running event loop and
# then driven with loop.run_until_complete(), in which case there
# is no current task to record as the waiter.
if events._get_running_loop() is loop:
self._cur_task = current_task(loop)
else:
self._cur_task = None
todo = {ensure_future(aw, loop=loop) for aw in set(aws)}
for f in todo:
f.add_done_callback(self._handle_completion)
Expand Down
16 changes: 16 additions & 0 deletions Lib/test/test_asyncio/test_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -1770,6 +1770,22 @@ async def coro():
futs = asyncio.as_completed([a])
list(futs)

def test_as_completed_outside_running_loop(self):
# gh-157856: as_completed() must not require a running event loop
# when the iterator is created, only when it is driven.
loop = self.new_test_loop()
self.addCleanup(asyncio.set_event_loop, None)
asyncio.set_event_loop(loop)

async def coro(v):
await asyncio.sleep(0)
return v

tasks = [loop.create_task(coro(v)) for v in (1, 2)]
futs = asyncio.as_completed(tasks)
results = [loop.run_until_complete(f) for f in futs]
self.assertEqual(sorted(results), [1, 2])

def test_as_completed_coroutine_use_running_loop(self):
loop = self.new_test_loop()

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix :func:`asyncio.as_completed` raising :exc:`RuntimeError` ("no running
event loop") when the iterator is created outside of a running event loop and
driven with :meth:`loop.run_until_complete() <asyncio.loop.run_until_complete>`.
Loading