我想实现一个这样的泛型类:
S = TypeVar("S")
T = TypeVar("T", bound=OtherParametrizedClass)
class MyClass(Generic[T[S]]):
def some_method(param: S) -> None:
pass
我已经尝试了以下方法:
S = TypeVar("S")
T = TypeVar("T", bound=OtherParametrizedClass)
class MyClass(Generic[S, T[S]]):
def some_method(param: S) -> None:
pass
def other_method(param: T) -> None:
pass
它与MyPy一起按预期工作。但是,当 Python 解释器运行此代码时,它会给我以下错误:
TypeError: 'TypeVar' object is not subscriptable.
正如我发现的,这意味着TypeVar
没有实现[]
运算符。
有没有人知道如何获得同时满足mypy和Python解释器的解决方案?
编辑: 我还尝试了以下方法:
S = TypeVar("S")
T = TypeVar("T", bound=OtherParametrizedClass[S])
class MyClass(Generic[T]):
def some_method(param: S) -> None:
pass
def other_method(param: T) -> None:
pass
Python 解释器不会给出任何错误/警告。然而,mypy抱怨第二行:
Invalid type "S"
我不确定我是否确切地理解您要实现的目标。
基本上有两个问题:
- 为什么需要定义
T
? - 为什么是
MyClass
Generic[T]
而不是Generic[S]
?
第二个问题是关键:我认为从根本上说,你做错的是你试图制造MyClass
Generic[T]
,而它应该只是Generic[S]
,此时你甚至不需要定义T
。other_method
可以返回OtherParametrizedClass[S]
.
下面是一个我认为可以实现您想要实现的示例:
import dataclasses
from typing import Generic, TypeVar
N = TypeVar("N", int, float)
@dataclasses.dataclass
class Adder(Generic[N]):
to_add: N
def add(self, value: N) -> N:
return value + self.to_add
class Foo(Generic[N]):
def get_adder(self, to_add: N) -> Adder[N]:
return Adder(to_add)
从我的示例到您的示例的名称映射:
N
S
Adder
OtherParametrizedClass
Foo
MyClass
Foo.get_adder
MyClass.other_method