首页 > 解决方案 > 从包装类推断类型注释

问题描述

鉴于以下类关系,我希望 mypy 能够推断出它x是 type int。泛型和 TypeVars 在这里似乎没有太大帮助。ParamSpec 看起来很有希望,但 mypy 还不支持它。有任何想法吗?

from typing import Generic, TypeVar

T = TypeVar('T')

class A:
    def __call__(self) -> int:
        ...

class Wrapper(Generic[T]):
    def __init__(self, typ: T) -> None:
        self._typ = typ

    def __call__(self) -> ...:
        return self._typ()()

x = Wrapper(A)()

标签: pythonmypy

解决方案


您可以使用通用回调协议来定义可调用对象。协变TypeVar参数化协议和通用包装类。像这样:

from typing import Generic, TypeVar, Protocol, Type

T = TypeVar('T', covariant=True)


class CallableProto(Protocol[T]):
    def __call__(self) -> T:
        ...

class A:
    def __call__(self) -> int:
        ...

class Wrapper(Generic[T]):
    def __init__(self, typ: Type[CallableProto[T]]) -> None:
        self._typ = typ

    def __call__(self) -> T:
        return self._typ()()


x = Wrapper(A)()
# reveal_type(x)  # Revealed type is "builtins.int*"

推荐阅读