Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How annotate a function that takes another function as parameter?

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

like image 808
K.Mulier Avatar asked Nov 09 '18 14:11

K.Mulier


People also ask

Can we use a function as a parameter of another function?

We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer. This process is known as call by reference as the function parameter is passed as a pointer that holds the address of arguments.

What Python functions accepts another function as a parameter?

A function that accepts another function as its parameter is called a Higher-order function.

How do you pass a function as a parameter in Python?

If you want to pass a method of a class as an argument but don't yet have the object on which you are going to call it, you can simply pass the object once you have it as the first argument (i.e. the "self" argument). Show activity on this post. Outputs: Running parameter f().

What is __ annotations __ in Python?

Annotations were introduced in Python 3.0 originally without any specific purpose. They were simply a way to associate arbitrary expressions to function arguments and return values. Years later, PEP 484 defined how to add type hints to your Python code, based off work that Jukka Lehtosalo had done on his Ph.


1 Answers

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)
like image 113
Alex Avatar answered Sep 30 '22 01:09

Alex