从包装 class 推断类型注释

Infer type annotation from wrapped class

给定以下 class 关系,我希望 mypy 能够推断出 xint 类型。 Generics 和 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)()

您可以使用泛型 callback protocol 来定义可调用对象。协变 TypeVar 来参数化协议和通用包装器 class。像这样:

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*"