Python 如何在类型提示中指定函数类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37835179/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:59:34  来源:igfitidea点击:

How can I specify the function type in my type hints?

pythonpython-3.xpython-3.5type-hintingmypy

提问by Jon

I want to use type hints in my current Python 3.5 project. My function should receive a function as parameter.

我想在我当前的 Python 3.5 项目中使用类型提示。我的函数应该接收一个函数作为参数。

How can I specify the type function in my type hints?

如何在类型提示中指定类型函数?

import typing

def my_function(name:typing.AnyStr, func: typing.Function) -> None:
    # However, typing.Function does not exist.
    # How can I specify the type function for the parameter `func`?

    # do some processing
    pass

I checked PEP 483, but could not find a function type hint there.

我检查了PEP 483,但在那里找不到函数类型提示。

回答by Dimitris Fasarakis Hilliard

As @jonrsharpenoted in a comment, this can be done with typing.Callable:

正如@jonrsharpe在评论中指出的那样,这可以通过以下方式完成typing.Callable

from typing import AnyStr, Callable

def my_function(name: AnyStr, func: Callable) -> None:

Issue is, Callableon it's own is translated to Callable[..., Any]which means:

问题是,Callable它本身被翻译成Callable[..., Any]这意味着:

A callable takes any number of/type ofarguments and returns a value of any type. In most cases, this isn't what you want since you'll allow pretty much any function to be passed. You want the function parameters and return types to be hinted too.

可调用对象接受任意数量/类型的参数并返回任意类型的值。在大多数情况下,这不是您想要的,因为您将允许传递几乎任何函数。您还希望提示函数参数和返回类型。

That's why many typesin typinghave been overloaded to support sub-scripting which denotes these extra types. So if, for example, you had a function sumthat takes two ints and returns an int:

这就是为什么许多typesintyping已被重载以支持表示这些额外类型的子脚本。因此,例如,如果您有一个sum接受两个ints 并返回一个 s的函数int

def sum(a: int, b: int) -> int: return a+b

Your annotation for it would be:

你对它的注释是:

Callable[[int, int], int]

that is, the parameters are sub-scripted in the outer subscription with the return type as the second element in the outer subscription. In general:

也就是说,参数在外部订阅中被下标,返回类型作为外部订阅中的第二个元素。一般来说:

Callable[[ParamType1, ParamType2, .., ParamTypeN], ReturnType]

回答by Hallsville3

Another interesting point to note is that you can use the built in function type()to get the type of a built in function and use that. So you could have

另一个需要注意的有趣点是您可以使用内置函数type()来获取内置函数的类型并使用它。所以你可以有

def f(my_function: type(abs)) -> int:
    return my_function(100)

Or something of that form

或者那种形式的东西