Skip to content

Commit 996859a

Browse files
authored
bpo-34790: [docs] Passing coroutines to asyncio.wait() can be confusing. (GH-9543)
1 parent 22ef31d commit 996859a

File tree

2 files changed

+37
-4
lines changed

2 files changed

+37
-4
lines changed

Doc/library/asyncio-task.rst

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -472,14 +472,20 @@ Waiting Primitives
472472
return_when=ALL_COMPLETED)
473473

474474
Run :ref:`awaitable objects <asyncio-awaitables>` in the *aws*
475-
sequence concurrently and block until the condition specified
475+
set concurrently and block until the condition specified
476476
by *return_when*.
477477

478478
If any awaitable in *aws* is a coroutine, it is automatically
479-
scheduled as a Task.
479+
scheduled as a Task. Passing coroutines objects to
480+
``wait()`` directly is deprecated as it leads to
481+
:ref:`confusing behavior <asyncio_example_wait_coroutine>`.
480482

481483
Returns two sets of Tasks/Futures: ``(done, pending)``.
482484

485+
Usage::
486+
487+
done, pending = await asyncio.wait(aws)
488+
483489
The *loop* argument is deprecated and scheduled for removal
484490
in Python 4.0.
485491

@@ -514,9 +520,35 @@ Waiting Primitives
514520
Unlike :func:`~asyncio.wait_for`, ``wait()`` does not cancel the
515521
futures when a timeout occurs.
516522

517-
Usage::
523+
.. _asyncio_example_wait_coroutine:
524+
.. note::
518525

519-
done, pending = await asyncio.wait(aws)
526+
``wait()`` schedules coroutines as Tasks automatically and later
527+
returns those implicitly created Task objects in ``(done, pending)``
528+
sets. Therefore the following code won't work as expected::
529+
530+
async def foo():
531+
return 42
532+
533+
coro = foo()
534+
done, pending = await asyncio.wait({coro})
535+
536+
if coro in done:
537+
# This branch will never be run!
538+
539+
Here is how the above snippet can be fixed::
540+
541+
async def foo():
542+
return 42
543+
544+
task = asyncio.create_task(foo())
545+
done, pending = await asyncio.wait({task})
546+
547+
if task in done:
548+
# Everything will work as expected now.
549+
550+
Passing coroutine objects to ``wait()`` directly is
551+
deprecated.
520552

521553

522554
.. function:: as_completed(aws, \*, loop=None, timeout=None)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Document how passing coroutines to asyncio.wait() can be confusing.

0 commit comments

Comments
 (0)