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

标签 python python-3.x type-hinting mypy python-typing

如何将变量的类型提示指定为函数类型?没有 typing.Function,我在相关的 PEP 中找不到任何内容,PEP 483 .

最佳答案

作为 @jonrsharpe在评论中注明,这可以通过 typing.Callable 来完成:

from typing import Callable

def my_function(func: Callable):

注意: Callable 本身等同于 Callable[..., Any]。 这样的 Callable 接受 any 数量和类型的参数 (...) 并返回 any 类型的值(任何)。如果这太不受约束,还可以指定输入参数列表的类型和返回类型。

例如,给定:

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

对应的注解是:

Callable[[int, int], int]

即参数在外订阅中下标,返回类型为外订阅中的第二个元素。一般来说:

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

关于python - 如何在类型提示中指定函数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37835179/

相关文章:

python - 获得范围内频率平均值的最快方法

python - pipwheel如何解决传递依赖?

python - datetime 函数,将 yyyymm 输入转换为月初和月末日期输出

python - 如何使用python包创建链接

Python测试整个脚本

python-3.x - Plotly 无法为多个跟踪器返回选定数据点的信息

PHP 7 接口(interface),返回类型提示和 self

python - pip 卸载时出现权限错误

python - 实例化一个 TypeVar 类型

php - 将字符串传递到具有类型提示的方法时出错