如何在Python中注释'apply'的类型?
可以在Python中精确地注释apply函数的类型吗 如果没有类型化,则函数为如何在Python中注释'apply'的类型?,python,mypy,Python,Mypy,可以在Python中精确地注释apply函数的类型吗 如果没有类型化,则函数为 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的第一个
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,))
另一方面,即使元组[T]以某种方式表示了一个类型列表,也不是说元组[T]没有什么意义。如果您查看,您可以看到签名可调用[[Arg1Type,Arg2Type],ReturnType]中要求的列表是一个变量类型列表
from typing import *
T = TypeVar('T')
S = TypeVar('S')
def apply(f: [[T],S], args: Tuple[T]) -> S:
return f(*args)
虽然这适用于单参数函数,但不允许f是多个参数的函数。您能指定一个函数示例和将被传递的参数吗?当然!在最初的问题中,我举了两个呼叫站点的例子。