【问题标题】:How annotate a function that takes another function as parameter?如何注释将另一个函数作为参数的函数?
【发布时间】:2021-10-15 23:02:19
【问题描述】:

我正在尝试在 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))

输出只是打印15

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

【问题讨论】:

  • from typing import Callable
  • 这是注释“函数对象”的标准方式吗?
  • 来自文档:Callable 可用于“期望特定签名的回调函数的框架”

标签: python python-3.x annotations


【解决方案1】:

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

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

from typing import Callable

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

【讨论】:

  • 谢谢,我只是在搜索文档。回来发布这个。
  • 谢谢@Alex。我现在明白了:Callable[[Arg1Type, Arg2Type, ... ], ReturnType]
  • 如果给定的func 并不总是相同怎么办?假设你有 def func_c(s:str) -> float: return 0.1,现在你想调用 func_b 像:print(func_b(func_c)),那么 Callable[[int], int] 是不够的。你会怎么做?
  • @TasosGlrs 您可以使用 Any 类型 docs.python.org/3/library/typing.html#the-any-type 或者您可以保留 Callable 类型未参数化。
【解决方案2】:

不应该只是function吗?

>>> type(func_a)
function

【讨论】:

  • 也许,我不知道。 @Sebastian Loehner 建议使用 Callable。你建议function。谁是对的?
  • Callable 是正确的。如果您尝试使用 function 注释函数,您将收到错误,因为未定义 function(尝试:def a(f: function): pass)。虽然每个函数的类型都是function 类的实例,但类型注释并不(总是)使用type(...) 函数返回的值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 2019-10-09
  • 1970-01-01
  • 1970-01-01
  • 2013-04-13
相关资源
最近更新 更多