Created
March 28, 2015 23:45
-
-
Save jamesls/78f334ae994c9caa577d to your computer and use it in GitHub Desktop.
Asyncio and coroutines confusion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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