是否有可能(精确地)注释Python中“应用”函数的类型?
未键入,函数为
def apply(f, args):
return f(*args)
我想写类似的东西
from typing import *
T = TypeVar('T')
S = TypeVar('S')
def apply(f: Callable[T,S], args: Tuple[T]) -> S:
return f(*args)
但是这不起作用。 mypy
至少抱怨Callable
的第一个参数必须是列表...
[如何使用apply
的两个示例:
def add(x: int, y: int) -> int:
return x + y
def negate(x: int) -> int:
return -x
apply(add, (x,y))
apply(negate, (x,))
P.S。即使Tuple[T]
以某种方式表示类型列表,也不是T
不太有意义。
[如果您查看doc,您会发现签名Callable[[Arg1Type, Arg2Type], ReturnType]
中要求的列表是变量类型的列表
from typing import *
T = TypeVar('T')
S = TypeVar('S')
def apply(f: [[T],S], args: Tuple[T]) -> S:
return f(*args)