从包装类推断类型注释



给定以下类关系,我希望mypy能够推断x的类型为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)()

您可以使用通用回调协议来定义可调用对象。以及协变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*"

最新更新