我正在尝试使用 mypy 在 python 2.7 中注释和定义我的类型。 我似乎找不到任何描述如何将函数作为参数传递并记录其类型的文档。 例如,在 Scala 中,我可以定义一个函数类型,将两个整数映射到一个布尔值:
def exampleFunction(f: (Int,Int) => Boolean) = {
// Do Something
}
mypy中有类似的表示法吗?也许是这样的?
def exampleFunction(f):
# type: ((int, int) -> bool) -> None
# Do Something
当函数类型为参数时,注释函数类型的最佳实践是什么?
你可以将你的函数写成
from typing import Callable
def exampleFunction(f: Callable[[int, int], bool]):
# Do Something
一般来说,语法是
Callable[[<parameters>], <return type>]
一些示例,针对 3 种可能的函数类型
f
带参数和返回值g
仅返回h
仅带参数def f(i: int) -> bool:
return i > 0
def check_f(function: Callable[[int], bool]):
...
def g() -> bool:
return True
def check_g(function: Callable[[], bool]):
...
def h(i: int, j: int):
pass
def check_h(function: Callable[[int, int], None]):
...
Mypy 说:
Success: no issues found in 1 source file