简体   繁体   English

您可以使用 mypy 将函数的类型定义为 python 中的参数吗?

[英]Can you define a type for a function as an argument in python using mypy?

I'm trying to annotate and define my types in python 2.7 using mypy.我正在尝试使用 mypy 在 python 2.7 中注释和定义我的类型。 I can't seem to find any documentation describing how one might pass a function as an argument and record its type.我似乎找不到任何描述如何将函数作为参数传递并记录其类型的文档。 For example, in Scala I can define a function type which maps two ints to a boolean as:例如,在 Scala 中,我可以定义一个将两个整数映射到一个布尔值的函数类型:

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

Is there similar notation in mypy? mypy中有类似的符号吗? Something like this perhaps?也许是这样的?

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

What is the best practice for annotating function types when they are arguments?当它们是参数时注释函数类型的最佳实践是什么?

For anyone stumbling upon this question when googling how to give a type to a function (in Python 3, havent tested for 2), this could be useful:对于在谷歌搜索如何为函数提供类型时遇到这个问题的任何人(在 Python 3 中,尚未测试 2),这可能很有用:

In principle, the syntax is Callable[[<parameters>], <return type>]原则上,语法是Callable[[<parameters>], <return type>]

Some examples, for the 3 possible types of functions一些例子,对于 3 种可能的函数类型

  1. function f with parameters and return带参数的函数f并返回
  2. function g with only return函数g只返回
  3. function h with only parameters只有参数的函数h

I made 3 check-functions, that take the function as input.我制作了 3 个检查函数,将函数作为输入。 I want to illustrate what type to give to a parameter if this parameter is a function.如果这个参数是一个函数,我想说明给参数什么类型。

from typing import Callable


    def f(i: int) -> bool:
        return i > 0

    def g() -> bool:
        return True

    def h(i: int, j: int):
        pass

    def check_f(function: Callable[[int], bool]):
        print(function(1))

    def check_g(function: Callable[[], bool]):
        print(function())

    def check_h(function: Callable[[int, int], None]):
        print(function(1, 1))

    check_f(f)
    check_g(g)
    check_h(h)

prints印刷

True
True
None

Mypy says: Success: no issues found in 1 source file Mypy 说: Success: no issues found in 1 source file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM