【问题标题】:Python asyncio, futures and yield fromPython asyncio、futures 和 yield from
【发布时间】:2014-01-10 19:40:38
【问题描述】:

考虑以下程序(在 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。然后在yield fromrun_test() 中爆炸

  2. 为什么我需要评估 future.result() 中的 run_test 来检索引发异常的值? docsyield from <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)

好的,我找到了“问题”。 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

【问题讨论】:

  • 这在 Python 3.3 中有效还是只是测试版中的一个错误?
  • 我没有安装 3.3.. 会检查。
  • 关于第一个问题,哪里炸了?在future = yield from f(x)res = future.result()
  • @delnan on yield from f(x) .. float is not iterable。事实上,没有装饰器,fast_sqrt 将返回一个float(不再是future)。
  • @oberstet 我发现这非常很难相信(它使我对asyncio 的理解无效,否则就解释了你的描述)。您能否仔细检查此处发布的代码是否是导致该问题的代码?换句话说,请复制并粘贴此问题的代码,删除@coroutine,运行它并显示回溯。我自己会这样做,但我既没有可用的 3.4 beta 也没有包管理器来测试 asyncio-for-3.3。

标签: python future yield coroutine python-asyncio


【解决方案1】:

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

  1. 没有装饰器,fast_sqrt(x) 像普通函数一样运行并返回浮点数的未来(不管上下文)。该未来被future = yield from ... 消耗,留下future 一个浮点数(它没有result 方法)。

  2. 使用装饰器,调用f(x) 会通过@coroutine 创建的包装函数。这个包装函数调用fast_sqrt 并使用yield from &lt;future&gt; 构造为您解包生成的future。因此,这个包装函数本身就是一个协程。因此,future = yield from ... 等待 那个 协程,并再次给 future 留下一个浮点数。

关于#2,yield from &lt;future&gt;确实工作(如上所述,你在使用未装饰的fast_sqrt时使用它),你也可以写:

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

(模它不适用于 fast_sqrt 所写的,并且不会获得额外的异步性,因为未来在从 coro_returning_a_future 返回时已经完成。)

您的核心问题似乎是您混淆了协程和期货。您的两个 sqrt 实现都尝试成为导致期货的异步任务。 根据我有限的经验,这不是人们通常编写异步代码的方式。它允许您将未来的构建和未来所代表的计算拉到两个独立的异步任务中。但是你不这样做(你返回一个已经完成的未来)。而且大多数时候,这不是一个有用的概念:如果您必须异步进行一些计算,您要么将其编写为协程(可以暂停)你将它推入另一个线程并使用yield from &lt;future&gt; 与它通信。两者都不是。

要使平方根计算异步,只需编写一个常规协程进行计算并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)

【讨论】:

  • 我知道如何处理协程和没有 Futures (github.com/oberstet/scratchbox/blob/master/python/asyncio/…),但是这个 需要 函数被修饰。我正在寻找一个有期货但没有装饰器的解决方案(非侵入性 rgd API)。
  • @oberstet 你可以编写一个普通的非协程函数来返回一个未来。您可以编写一个返回普通值并同步使用它们的普通函数。你可以编写一个没有装饰器的协程(尽管你显然仍然需要遵循关于yield from 等的异步约定)。我不知道“rgd API”是什么,但如果您想更详细地描述您的问题,您可以打开另一个问题。
  • 我的“问题”是slow_srqt 中的yield from asyncio.sleep 自动使其成为协程。我正在寻找这 4 个变体:github.com/oberstet/scratchbox/blob/master/python/asyncio/…
猜你喜欢
  • 1970-01-01
  • 2014-04-22
  • 2014-01-28
  • 2016-06-01
  • 2023-01-25
  • 2020-05-09
  • 2014-11-16
  • 2019-01-06
  • 2018-04-29
相关资源
最近更新 更多