Ban đầu tôi đã có một số mã tổng hợp kết quả vào danh sách. Khi tôi refactored mã này sử dụng một danh sách comphrehension, tôi nhận được kết quả bất ngờ:Tại sao tôi nhận được kết quả khác khi sử dụng danh sách hiểu với coroutines với asyncio?
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 huh():
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(huh()))
Nếu tôi chạy mã này tôi nhận được kết quả này:
$ python3.4 /tmp/test.py
['foo', 'foo', 'foo']
['foo', 'foo', 'foo']
<generator object <listcomp> at 0x104eb1360>
Tại sao tôi nhận kết quả khác nhau cho ba huh()
chức năng?
[Whoa, nó có thể tái sản xuất.] (Http://ideone.com/k2MsG9) Tôi đã không mong đợi điều đó. Làm sao địa ngục? – user2357112