【问题标题】:What is the value of await awaitable_object?await awaitable_object 的值是多少?
【发布时间】:2017-11-13 19:49:00
【问题描述】:

asyncio 发布之前,我一直在使用基于生成器的协程。

现在我正在尝试学习 Python 3.5 中引入的新 async/await 功能。这是我的测试程序之一。

class Await3:
    def __init__(self, value):
        self.value = value
    def __await__(self):
        return iter([self.value, self.value, self.value])

async def main_coroutine():
    x = await Await3('ABC')
    print("x =", x)

def dummy_scheduler(cobj):
    snd = None
    try:
        while True:
            aw = cobj.send(snd)
            #snd = 42
            print("got:", aw)
    except StopIteration:
        print("stop")

dummy_scheduler(main_coroutine())

它的输出是:

got: ABC
got: ABC
got: ABC
x = None
stop

x 的值是await awaitable_object 表达式的结果。为什么这个值是None,我怎样才能把它设置成我想要的值?

我只能找到await couroutine() 的值是由协程的返回值决定的,但这不是我的情况。

取消注释 snd = 42 不起作用。错误是AttributeError: 'list_iterator' object has no attribute 'send'

【问题讨论】:

    标签: python async-await


    【解决方案1】:

    如果您要手动实现一个带有__await__ 方法的类,则您的类实例上await 表达式的返回值将是用于构造StopIteration 异常的任何参数迭代器的结尾,如果没有参数,则为 None

    您无法使用 return iter(some_list) 之类的东西来控制 StopIteration 参数。您需要编写自己的迭代器。我想说把它写成一个生成器和return这个值:

    class Await3:
        def __init__(self, value):
            self.value = value
        def __await__(self):
            yield self.value
            yield self.value
            yield self.value
            return whatever
    

    这将抛出StopIteration(whatever) 来结束迭代,但如果您想以简单的方式做事,您首先应该编写一个async 函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-24
      • 2013-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2012-03-06
      相关资源
      最近更新 更多