Skip to content

Commit 56b8ea6

Browse files
authored
Updated code example for asyncio.gather (GH-20604)
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".
1 parent 65d180d commit 56b8ea6

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
@@ -358,32 +358,35 @@ Running Tasks Concurrently
358358
async def factorial(name, number):
359359
f = 1
360360
for i in range(2, number + 1):
361-
print(f"Task {name}: Compute factorial({i})...")
361+
print(f"Task {name}: Compute factorial({number}), currently i={i}...")
362362
await asyncio.sleep(1)
363363
f *= i
364364
print(f"Task {name}: factorial({number}) = {f}")
365+
return f
365366

366367
async def main():
367368
# Schedule three calls *concurrently*:
368-
await asyncio.gather(
369+
L = await asyncio.gather(
369370
factorial("A", 2),
370371
factorial("B", 3),
371372
factorial("C", 4),
372373
)
374+
print(L)
373375

374376
asyncio.run(main())
375377

376378
# Expected output:
377379
#
378-
# Task A: Compute factorial(2)...
379-
# Task B: Compute factorial(2)...
380-
# Task C: Compute factorial(2)...
380+
# Task A: Compute factorial(2), currently i=2...
381+
# Task B: Compute factorial(3), currently i=2...
382+
# Task C: Compute factorial(4), currently i=2...
381383
# Task A: factorial(2) = 2
382-
# Task B: Compute factorial(3)...
383-
# Task C: Compute factorial(3)...
384+
# Task B: Compute factorial(3), currently i=3...
385+
# Task C: Compute factorial(4), currently i=3...
384386
# Task B: factorial(3) = 6
385-
# Task C: Compute factorial(4)...
387+
# Task C: Compute factorial(4), currently i=4...
386388
# Task C: factorial(4) = 24
389+
# [2, 6, 24]
387390

388391
.. note::
389392
If *return_exceptions* is False, cancelling gather() after it

0 commit comments

Comments
 (0)