相关疑难解决方法(0)

如何使用 AsyncGenerator 和 AsyncContextManager 正确指定类型提示

考虑下面的代码

import contextlib
import abc
import asyncio

from typing import AsyncContextManager, AsyncGenerator, AsyncIterator


class Base:

    @abc.abstractmethod
    async def subscribe(self) -> AsyncContextManager[AsyncGenerator[int, None]]:
        pass

class Impl1(Base):

    @contextlib.asynccontextmanager
    async def subscribe(self) ->  AsyncIterator[ AsyncGenerator[int, None] ]: <-- mypy error here

        async def _generator():
            for i in range(5):
                await asyncio.sleep(1)
                yield i
                    
        yield _generator()
Run Code Online (Sandbox Code Playgroud)

对于Impl1.subscribemypy 给出错误

Signature of "subscribe" incompatible with supertype "Base"
Run Code Online (Sandbox Code Playgroud)

在上述情况下指定类型提示的正确方法是什么?或者 mypy 这里错了?

python type-hinting mypy

15
推荐指数
1
解决办法
1万
查看次数

标签 统计

mypy ×1

python ×1

type-hinting ×1