简体   繁体   English

如何注释以另一个函数为参数的函数?

[英]How annotate a function that takes another function as parameter?

I'm experimenting with type annotations in Python.我正在尝试在 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 .输出只是打印15

How should I annotate the func parameter in func_b( ) ?我应该如何注释func_b( )func参数?

You can use the typing module for Callable annotations.您可以将typing模块用于Callable注释。

The Callable annotation is supplied a list of argument types and a return type: Callable注解提供了一个参数类型列表和一个返回类型:

from typing import Callable

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

Shouldn't it just be function ?它不应该只是function吗?

>>> type(func_a)
function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何注释 Python function 以暗示它采用与另一个 function 相同的 arguments? - How do I annotate a Python function to hint that it takes the same arguments as another function? function 如何将另一个 function WITH arguments 作为参数? - How can a function takes another function WITH arguments, as a parameter? 如何使用 str 默认值注释采用 AnyStr 的 function? - How do I annotate a function that takes AnyStr with a str default value? 如何注释arguments转发给另一个function的类型? - How to annotate the type of arguments forwarded to another function? 如何使用另一个函数的返回类型来注释Python函数? - How to annotate Python function using return type of another function? 如何注释 function 参数的最大限制 - How can I annotate a maximum limit to a function parameter Function 接受可选参数 - Function that takes in optional parameter Python 为 Function 参数注释两个精确的字符串 - Python Annotate Two Exact Strings for Function Parameter 如何注释采用可变长度元组的函数? (可变元组类型注释) - How to annotate function that takes a tuple of variable length? (variadic tuple type annotation) 如何记录将函数作为Sphinx参数的函数? - How can I document a function which takes a function as a parameter with Sphinx?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM