Python:同时用于多个参数的 TypeVar

EZL*_*ner 5 python type-hinting python-3.x

有没有办法让TypeVar(或其他格式)捕获函数的所有参数?例如,假设我想包装一个通用函数,使其所有参数都在一个元组中给出:

def invoke(f: Callable[..., T], args: Tuple[...]) -> T:
    return f(*args)
Run Code Online (Sandbox Code Playgroud)

只是...我将使用静态类型检查来强制 be 的内容Tuple与函数的参数具有相同的类型,而不是省略号 ( )。

谢谢。

EZL*_*ner 1

答案是肯定的,只是不配合TypeVar。应该使用ParamSpec

from typing import ParamSpec, TypeVar, Callable
P = ParamSpec('P')
RT = TypeVar('RT')

def invoke(f: Callable[P, RT], args: P.args) -> RT:
    return f(*args)

# Or, makes more sense:

def invoke(f: Callable[P, RT], args: P.args, **kwargs: P.kwargs) -> RT:
    return f(*args, **kwargs)

Run Code Online (Sandbox Code Playgroud)

请注意,对于 python < 3.10,应该从而typing_extensions不是typing.