如何在Python中注释'apply'的类型?

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

是否有可能(精确地)注释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不太有意义。

python mypy
1个回答
-1
投票

[如果您查看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)
© www.soinside.com 2019 - 2024. All rights reserved.