说我有一个类型:
class MyType(Generic[T, U]):
def foo(self, *args: T) -> U:
pass
m = MyType[tuple[int, bool], str]
我希望能够提供如下参数:
m.foo(1, True)
而不是
m.foo((1, True))
有没有办法在使用泛型的方法中执行此操作,因此如果我有一个包含多个参数的类型,我可以在方法中将它们解压?
我知道我可以使用:
P = ParamSpec("P")
但是我想对 P.args 施加类型约束,以便它等于 T。
TypeVarTuple
就是你想要的:它收集未指定数量的类型参数,并允许你稍后解压它。
class MyType[*Ts, U]:
def foo(self, *args: *Ts) -> U:
...
m = MyType[int, bool, str]() # No extra brackets
reveal_type(m.foo(1, True)) # mypy => str
# Pyright => str
在 Python 3.10 或更早版本中:
from typing import Generic, TypeVar
from typing_extensions import TypeVarTuple, Unpack
Ts = TypeVarTuple('Ts')
U = TypeVar('U')
class MyType(Generic[*Ts, U]):
def foo(self, *args: Unpack[Ts]) -> U:
...