你可以使用 mypy 在 python 中定义函数的类型作为参数吗?

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

我正在尝试使用 mypy 在 python 2.7 中注释和定义我的类型。 我似乎找不到任何描述如何将函数作为参数传递并记录其类型的文档。 例如,在 Scala 中,我可以定义一个函数类型,将两个整数映射到一个布尔值:

def exampleFunction(f: (Int,Int) => Boolean) = {
  // Do Something
}

mypy中有类似的表示法吗?也许是这样的?

def exampleFunction(f):
    # type: ((int, int) -> bool) -> None
    # Do Something

当函数类型为参数时,注释函数类型的最佳实践是什么?

python python-2.7 mypy
1个回答
4
投票

简短回答:

你可以将你的函数写成

from typing import Callable


def exampleFunction(f: Callable[[int, int], bool]):
    # Do Something

一般来说,语法是

Callable[[<parameters>], <return type>]

更多示例:

一些示例,针对 3 种可能的函数类型

  1. 函数
    f
    带参数和返回值
  2. 函数
    g
    仅返回
  3. 函数
    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

© www.soinside.com 2019 - 2024. All rights reserved.