Skip to content

Instantly share code, notes, and snippets.

@jamesls
Created March 28, 2015 23:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesls/78f334ae994c9caa577d to your computer and use it in GitHub Desktop.
Save jamesls/78f334ae994c9caa577d to your computer and use it in GitHub Desktop.
Asyncio and coroutines confusion
import asyncio
@asyncio.coroutine
def coro():
return "foo"
# Writing the code without a list comp works,
# even with an asyncio.sleep(0.1).
@asyncio.coroutine
def good():
yield from asyncio.sleep(0.1)
result = []
for i in range(3):
current = yield from coro()
result.append(current)
return result
# Using a list comp without an async.sleep(0.1)
# works.
@asyncio.coroutine
def still_good():
return [(yield from coro()) for i in range(3)]
# Using a list comp along with an asyncio.sleep(0.1)
# does _not_ work.
@asyncio.coroutine
def bug():
yield from asyncio.sleep(0.1)
return [(yield from coro()) for i in range(3)]
loop = asyncio.get_event_loop()
print(loop.run_until_complete(good()))
print(loop.run_until_complete(still_good()))
print(loop.run_until_complete(bug()))
# Running this code gives:
# $ python3.4 /tmp/test.py
# ['foo', 'foo', 'foo']
# ['foo', 'foo', 'foo']
# <generator object <listcomp> at 0x104eb1360>
#
# I don't understand why the third function is different.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment