使用类型从方法中定义解包参数

问题描述 投票:0回答:1

说我有一个类型:

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。

python type-hinting
1个回答
0
投票

TypeVarTuple
就是你想要的:它收集未指定数量的类型参数,并允许你稍后解压它。

(游乐场链接:mypyPyright

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:
        ...
© www.soinside.com 2019 - 2024. All rights reserved.