Skip to content

Commit 2979f3a

Browse files
committed
Add footgun section.
1 parent 81252a1 commit 2979f3a

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

peps/pep-9999.rst

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,40 @@ intends to be very intuitive; users should be able to deduce the behavior of
288288
``yield from`` in an asynchronous generator based on their own background
289289
knowledge of ``yield from`` in synchronous generators.
290290

291+
Potential footguns
292+
------------------
293+
294+
Forgetting to ``await`` before ``yield from``
295+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
296+
297+
In :mod:`asyncio`, a :ref:`future <asyncio-future-obj>` object is natively
298+
iterable. This means that if one were trying to iterate over the result of a
299+
future, forgetting to :keyword:`await` the future may accidentally await the
300+
future itself, leading to a spurious error.
301+
302+
For example:
303+
304+
.. code-block:: python
305+
306+
import asyncio
307+
308+
async def steps():
309+
await asyncio.sleep(0.25)
310+
await asyncio.sleep(0.25)
311+
await asyncio.sleep(0.25)
312+
return [1, 2, 3]
313+
314+
async def generator():
315+
# Forgot to await!
316+
yield from asyncio.ensure_future(steps())
317+
318+
async def run():
319+
total = 0
320+
async for i in generator():
321+
# TypeError?!
322+
total += i
323+
print(total)
324+
291325
292326
Reference Implementation
293327
========================

0 commit comments

Comments
 (0)