Skip to content

Commit f38296f

Browse files
Updated code example for asyncio.gather (GH-20604) (GH-26120)
The previous example did not fully showcase the interest of using gather. Here the example showcases "the result is an aggregate list of returned values". (cherry picked from commit 56b8ea6) Co-authored-by: josephernest <[email protected]> Co-authored-by: josephernest <[email protected]>
1 parent 133013e commit f38296f

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

Doc/library/asyncio-task.rst

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -360,32 +360,35 @@ Running Tasks Concurrently
360360
async def factorial(name, number):
361361
f = 1
362362
for i in range(2, number + 1):
363-
print(f"Task {name}: Compute factorial({i})...")
363+
print(f"Task {name}: Compute factorial({number}), currently i={i}...")
364364
await asyncio.sleep(1)
365365
f *= i
366366
print(f"Task {name}: factorial({number}) = {f}")
367+
return f
367368

368369
async def main():
369370
# Schedule three calls *concurrently*:
370-
await asyncio.gather(
371+
L = await asyncio.gather(
371372
factorial("A", 2),
372373
factorial("B", 3),
373374
factorial("C", 4),
374375
)
376+
print(L)
375377

376378
asyncio.run(main())
377379

378380
# Expected output:
379381
#
380-
# Task A: Compute factorial(2)...
381-
# Task B: Compute factorial(2)...
382-
# Task C: Compute factorial(2)...
382+
# Task A: Compute factorial(2), currently i=2...
383+
# Task B: Compute factorial(3), currently i=2...
384+
# Task C: Compute factorial(4), currently i=2...
383385
# Task A: factorial(2) = 2
384-
# Task B: Compute factorial(3)...
385-
# Task C: Compute factorial(3)...
386+
# Task B: Compute factorial(3), currently i=3...
387+
# Task C: Compute factorial(4), currently i=3...
386388
# Task B: factorial(3) = 6
387-
# Task C: Compute factorial(4)...
389+
# Task C: Compute factorial(4), currently i=4...
388390
# Task C: factorial(4) = 24
391+
# [2, 6, 24]
389392

390393
.. note::
391394
If *return_exceptions* is False, cancelling gather() after it

0 commit comments

Comments
 (0)