gpt4 book ai didi

python - 覆盖父类(super class)型的协程时如何使用 mypy?

转载 作者:行者123 更新时间:2023-12-05 01:40:10 36 4
gpt4 key购买 nike

有一个类扩展了另一个类并覆盖了一个返回迭代器的协程:

class Repository:
async def run(self, query: Query) -> AsyncIterator[int]:
...

class MyRepository(Repository):
async def run(self, query: Query) -> AsyncIterator[int]:
...

运行 mypy 返回此错误:

error: Return type "AsyncIterator[int]" of "run" incompatible with return type "Coroutine[Any, Any, AsyncIterator[int]]" in supertype "Repository"

Coroutines are typed like normal functions ,所以我不确定正确的方法是什么。

使用 ABC 类无法解决问题:

class Repository(metaclass=ABCMeta):
@abstractmethod
async def run(self, query: Query) -> AsyncIterator[int]:

最佳答案

感谢 this issue 找到它:

I think you shouldn't make the protocol function async def, but just def. Conceptually, an async generator is a callable that returns an AsyncIterator (or more precisely, an AsyncGenerator). But an async def function without a yield returns an Awaitable of whatever its declared return type is, so that's how mypy interprets your protocol.

因此,将 async def run 更改为 def run 是可行的。

关于python - 覆盖父类(super class)型的协程时如何使用 mypy?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56947266/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com