【问题标题】:Python - Unable to create an awaitable class (awaitable instance gets created instead)Python - 无法创建可等待的类(而是创建了可等待的实例)
【发布时间】:2021-06-17 15:47:26
【问题描述】:

Python 文档建议可以实现__await__ 方法,该方法返回和迭代器,并且该类将变为可等待的。我测试了以下代码。

class AwaitableClass:
    async def set_attr(self):
        self.result = await some_coro()
    def __await__(self):
        return self.set_attr().__await__()

async def main():
    obj = await AwaitableClass() #obj gets bound to None
    obj = AwaitableClass() #Creates an instance of AwaitbleClass
    await obj #Calls __await__

有什么想法吗?

【问题讨论】:

  • 如果我理解您的问题,您正在尝试创建一个也是迭代器的类。我已经为此添加了一个答案,但如果我有误解,请告诉我,以便我更新我的答案。
  • 不清楚你的问题是什么。您希望您的代码做什么,而它目前没有做什么?据我所知,您已经以一种有意义的方式实现了 await,它返回一个可迭代对象,您可以成功地等待它。

标签: python-3.x python-asyncio


【解决方案1】:

您可以create async iterators/generators without classes,例如:

async def things():
    for i in range(10):
        yield i
        await asyncio.sleep(1)

async def run():
    async for thing in things:
        print(thing)

同样,对于do this in a class,你需要实现__aiter__函数和__anext__coro函数。喜欢:

class TestImplementation:
    def __init__(self):
        self.count = 0

    def __aiter__(self):
        return self

    async def __anext__(self):
        self.count += 1
        if self.count > 10:
            raise StopAsyncIteration
        await asyncio.sleep(1)
        return self.count

async def run():
    async for thing in TestImplementation():
        print(thing)

【讨论】:

    猜你喜欢
    • 2022-10-19
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多