Skip to content

Commit e0a41a5

Browse files
GH-124639: add back loop param to staggered_race (#124700)
1 parent c00964e commit e0a41a5

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

Lib/asyncio/staggered.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
class _Done(Exception):
1212
pass
1313

14-
async def staggered_race(coro_fns, delay):
14+
async def staggered_race(coro_fns, delay, *, loop=None):
1515
"""Run coroutines with staggered start times and take the first to finish.
1616
1717
This method takes an iterable of coroutine functions. The first one is
@@ -82,7 +82,13 @@ async def run_one_coro(this_index, coro_fn, this_failed):
8282
raise _Done
8383

8484
try:
85-
async with taskgroups.TaskGroup() as tg:
85+
tg = taskgroups.TaskGroup()
86+
# Intentionally override the loop in the TaskGroup to avoid
87+
# using the running loop, preserving backwards compatibility
88+
# TaskGroup only starts using `_loop` after `__aenter__`
89+
# so overriding it here is safe.
90+
tg._loop = loop
91+
async with tg:
8692
for this_index, coro_fn in enumerate(coro_fns):
8793
this_failed = locks.Event()
8894
exceptions.append(None)

Lib/test/test_asyncio/test_staggered.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,25 @@ async def coro(index):
121121
self.assertIsInstance(excs[0], ValueError)
122122
self.assertIsNone(excs[1])
123123

124+
def test_loop_argument(self):
125+
loop = asyncio.new_event_loop()
126+
async def coro():
127+
self.assertEqual(loop, asyncio.get_running_loop())
128+
return 'coro'
129+
130+
async def main():
131+
winner, index, excs = await staggered_race(
132+
[coro],
133+
delay=0.1,
134+
loop=loop
135+
)
136+
137+
self.assertEqual(winner, 'coro')
138+
self.assertEqual(index, 0)
139+
140+
loop.run_until_complete(main())
141+
loop.close()
142+
124143

125144
if __name__ == "__main__":
126145
unittest.main()

0 commit comments

Comments
 (0)