考虑下面的程序(在CPython的运行3.4.0b1):Python的ASYNCIO,期货收益率从
import math
import asyncio
from asyncio import coroutine
@coroutine
def fast_sqrt(x):
future = asyncio.Future()
if x >= 0:
future.set_result(math.sqrt(x))
else:
future.set_exception(Exception("negative number"))
return future
def slow_sqrt(x):
yield from asyncio.sleep(1)
future = asyncio.Future()
if x >= 0:
future.set_result(math.sqrt(x))
else:
future.set_exception(Exception("negative number"))
return future
@coroutine
def run_test():
for x in [2, -2]:
for f in [fast_sqrt, slow_sqrt]:
try:
future = yield from f(x)
print("\n{} {}".format(future, type(future)))
res = future.result()
print("{} result: {}".format(f, res))
except Exception as e:
print("{} exception: {}".format(f, e))
loop = asyncio.get_event_loop()
loop.run_until_complete(run_test())
我有2个(相关的)问题:
即使在装饰上
fast_sqrt
,Python似乎会优化掉fast_sqrt
中创建的Future,并返回一个普通的float
。然后在run_test()
在yield from
炸毁为什么我需要评估在
run_test
future.result()
检索火的值例外呢? docs说yield from <future>
“暂停协程,直到未来完成,然后返回未来的结果,或引发异常”。为什么我需要手动调整未来的结果?
这里是我所得到的:
[email protected] ~/scm/tavendo/infrequent/scratchbox/python/asyncio (master)
$ python3 -V
Python 3.4.0b1
[email protected] ~/scm/tavendo/infrequent/scratchbox/python/asyncio (master)
$ python3 test3.py
1.4142135623730951 <class 'float'>
<function fast_sqrt at 0x00B889C0> exception: 'float' object has no attribute 'result'
Future<result=1.4142135623730951> <class 'asyncio.futures.Future'>
<function slow_sqrt at 0x02AC8810> result: 1.4142135623730951
<function fast_sqrt at 0x00B889C0> exception: negative number
Future<exception=Exception('negative number',)> <class 'asyncio.futures.Future'>
<function slow_sqrt at 0x02AC8810> exception: negative number
[email protected] ~/scm/tavendo/infrequent/scratchbox/python/asyncio (master)
好吧,我发现了 “问题”。在slow_sqrt
中的yield from asyncio.sleep
将自动使其成为协程。等待需要以不同的方式完成:
def slow_sqrt(x):
loop = asyncio.get_event_loop()
future = asyncio.Future()
def doit():
if x >= 0:
future.set_result(math.sqrt(x))
else:
future.set_exception(Exception("negative number"))
loop.call_later(1, doit)
return future
所有4个变体都是here。
这是在Python3.3还是只是在测试版中的错误? – Mark
我没有3.3安装..会检查。 – oberstet
关于第一个问题,*哪里*爆炸了?在'未来=产量从f(x)'或'res = future.result()'? – delnan