Python asyncio、futures 和 yield from

标签 python future yield coroutine python-asyncio

考虑以下程序(在 CPython 3.4.0b1 上运行):

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 个(相关)问题:

  1. 即使在 fast_sqrt 上使用装饰器,Python 似乎优化了在 fast_sqrt 中创建的 Future总而言之,一个普通的float被退回。然后在 run_test() 中爆炸在yield from

  2. 为什么我需要评估future.result()run_test检索火异常的值? docsyield from <future> “暂停协程直到 future 完成,然后返回 future 的结果,或引发异常”。为什么我需要手动获取 future 的结果?

这是我得到的:

oberstet@COREI7 ~/scm/tavendo/infrequent/scratchbox/python/asyncio (master)
$ python3 -V
Python 3.4.0b1
oberstet@COREI7 ~/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
oberstet@COREI7 ~/scm/tavendo/infrequent/scratchbox/python/asyncio (master)

好的,我找到了“问题”。 yield from asyncio.sleepslow_sqrt将自动使其成为协程。等待需要以不同的方式完成:

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 .

最佳答案

关于 #1:Python 没有做这样的事情。请注意 fast_sqrt您编写的函数(即在任何装饰器之前)不是生成器函数、协程函数、任务或任何您想调用的函数。这是一个同步运行并返回您在 return 之后写入的内容的普通函数。陈述。取决于 @coroutine 的存在,非常不同的事情发生了。两者都导致相同的错误只是运气不好。

  1. 没有装饰器,fast_sqrt(x)像普通函数一样运行并返回 float 的 future (不管上下文)。那个 future 被future = yield from ...消耗了, 离开 future一个 float (没有 result 方法)。

  2. 装饰器,调用f(x)通过 @coroutine 创建的包装函数.此包装函数调用 fast_sqrt并使用 yield from <future> 为您解压由此产生的 future build 。因此,这个包装函数本身就是一个协程。因此,future = yield from ...等待 that 协程并离开 future又是一个 float 。

关于#2,yield from <future> 确实有效(如上所述,您在使用未修饰的 fast_sqrt 时使用它),您也可以这样写:

future = yield from coro_returning_a_future(x)
res = yield from future

(模数它不适用于写入的 fast_sqrt,并且不会为您带来额外的异步性,因为 future 在它从 coro_returning_a_future 返回时已经完成。)

您的核心问题似乎是您混淆了协程和 future 。您的两个 sqrt 实现都尝试成为导致 future 的异步任务。 根据我有限的经验,这不是通常编写 asyncio 代码的方式。它允许您将 future 的构建和 future 所代表的计算拉入两个独立的异步任务中。但是你不这样做(你返回一个已经完成的 future )。大多数时候,这不是一个有用的概念:如果您必须异步执行一些计算,您可以将其编写为协程(可以挂起)你将它插入另一个线程并使用 yield from <future> 与它通信.两者都不是。

要使平方根计算异步,只需编写一个常规协程来执行计算和 return结果(coroutine 装饰器会将 fast_sqrt 变成一个异步运行并可以等待的任务)。

@coroutine
def fast_sqrt(x):
   if x >= 0:
      return math.sqrt(x)
   else:
      raise Exception("negative number")

@coroutine # for documentation, not strictly necessary
def slow_sqrt(x):
   yield from asyncio.sleep(1)
   if x >= 0:
      return math.sqrt(x)
   else:
      raise Exception("negative number")

...
res = yield from f(x)
assert isinstance(res, float)

关于Python asyncio、futures 和 yield from,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20729104/

相关文章:

python - 获取代理ip地址scrapy用来爬取

scala - 对 future 作出 react

dictionary - future_map 中不能使用 tidy 函数?

Python:在不存储项目的情况下获取生成器中的项目数

python - 在实践中,Python 3.3 中新的 "yield from"语法的主要用途是什么?

ruby - 你如何使用 Ruby block 来有条件地执行某些东西?

python - 使用 Python 查找颜色的色调?

python - 如何使用distinct()为Django ListView中的每个标题项仅显示子模型中的一条记录

python - 关键 - 在 Travis CI 中运行时出错| pytest

c++ - 是否可以重新启动 boost::future?