Python 3:如何注释将另一个函数作为参数的函数?

K.M*_*ier 13 python annotations python-3.x

我正在尝试在 Python 中使用类型注释。大多数情况都非常清楚,除了那些将另一个函数作为参数的函数。

考虑以下示例:

from __future__ import annotations

def func_a(p:int) -> int:
    return p*5

def func_b(func) -> int: # How annotate this?
    return func(3)

if __name__ == "__main__":
    print(func_b(func_a))
Run Code Online (Sandbox Code Playgroud)

输出只是打印15.

我应该如何注释 中的func参数func_b( )

 
回答
谢谢@Alex 提供答案。该typing模块提供Callable注释(请参阅:python 文档)。对于我的示例,这给出了:

from __future__ import annotations
from typing import Callable

def func_a(p:int) -> int:
    return p*5

def func_b(func: Callable[[int], int]) -> int:
    return func(3)

if __name__ == "__main__":
    print(func_b(func_a))
Run Code Online (Sandbox Code Playgroud)

如您所见,Callable注释本身也被注释,遵循以下方案:

Callable[[Arg1Type, Arg2Type], ReturnType]
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 8

您可以将该typing模块用于Callable注释。

Callable注释提供的参数类型和返回类型的列表:

from typing import Callable

def func_b(func: Callable[[int], int]) -> int:
    return func(3)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢@Alex。我现在明白了:`Callable[[Arg1Type, Arg2Type, ... ], ReturnType]` (3认同)