继承具有受限 TypeVar 的泛型类

Zul*_*lan 6 python mypy python-typing

考虑一对简单的泛型类:

T = TypeVar("T", str, int)

class Base(Generic[T]):
    def __init__(self, v: T):
        self.v: T = v

    @property
    def value(self) -> T:
        return self.v

class Child(Base[T]):
    def __init__(self, v: T):
        super().__init__(v)

x = Child(123)
reveal_type(x.value)
Run Code Online (Sandbox Code Playgroud)

使用时T = TypeVar("T")效果符合预期。如图所示的限制TypeVar会产生以下错误:

error: Argument 1 to "__init__" of "Base" has incompatible type "str"; expected "T"
error: Argument 1 to "__init__" of "Base" has incompatible type "int"; expected "T"
note: Revealed type is 'builtins.int*'
Run Code Online (Sandbox Code Playgroud)

请注意,这reveal_type仍然有效。

另一个区别是受限制的TypeVar需要类型注释来进行self.v赋值,而不受限制的则不需要。

在完整的用例中,我实际上有Callable[[Any], T],但问题是相同的。

这是与mypy 0.910Python 3.9.7

hus*_*sic 2

绑定T到一个Union[int,str]应该做的工作:

T = TypeVar("T", bound=Union[str, int])


class Base(Generic[T]):

    def __init__(self, v: T):
        self.v: T = v

    @property
    def value(self) -> T:
        return self.v


class Child(Base[T]):

    def __init__(self, v: T):
        super().__init__(v)


x = Child(123)
reveal_type(x.value)
y = Child('a')
reveal_type(y.value)
Run Code Online (Sandbox Code Playgroud)