I'm experimenting with type annotations in Python. Most cases are pretty clear, except for those functions that take another function as parameter.

Consider the following example:

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))

The output simply prints 15.

How should I annotate the func parameter in func_b( )?

推荐答案

You can use the typing module for Callable annotations.

The Callable annotation is supplied a list of argument types and a return type:

from typing import Callable

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

Python-3.x相关问答推荐

TypeError:&Quot;Value&Quot;参数必须是标量、Dict或Series,但您传递了&Quot;Index&Quot;

循环遍历数据框以提取特定值

检测点坐标 - opencv findContours()

Django 模型类方法使用错误的 `self`

Python - 根据条件附加 NULL 值

不同的焦点顺序和堆叠顺序 tkinter

计算文档中所有关键字(单词和多词)出现的频率

使用 Python 截断并重新编号对应于特定 ID/组的列

Python rolling_corr 取消后,应该用什么方法来处理

Python 3 `str.__getitem__` 的计算复杂度是多少?

总结基于条件的值,如果不匹配则保留当前值

如何使用 Selenium by class_name 从大学橄榄球数据中抓取图像 url 列表

在python中循环处理时并行写入文件

使用 Python 3 按行进行分析

BeautifulSoup 的 Python 3 兼容性

PIL 在图像上绘制半透明方形覆盖

为什么 TensorFlow 的 `tf.data` 包会减慢我的代码速度?

使用 asyncio 的多个循环

有没有一种标准方法来确保 python 脚本将由 python2 而不是 python3 解释?

如何判断列表中的所有项目是否都是字符串