Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way in Python to ensure that one argument of my function is another function? [duplicate]

type annotation in the function arguments definition: I want to implement a High Order Function in python, and for that I would like to have explicit arguments type. Is there a way to show a 'function' type?

def high_order_math(a: Float, b: Float, func: function):
    return func(a,b)

Here are some findings, appreciate you all that have shared your knowledge

def high_order_math(a: float, b: float, func: Callable[[float, float], float]) -> float:
     return func(a, b)

high_order_math(1,2,3)

Traceback (most recent call last):

File "", line 1, in

File "", line 2, in high_order_math

TypeError: 'int' object is not callable

like image 760
Samuel Oliveira Avatar asked Jun 30 '20 18:06

Samuel Oliveira


People also ask

Does Python make a copy of arguments?

In Python, values live somewhere on their own, and have their own types, and variables are just names for those values. There is no copying, and there are no references to variables.

How do you pass an argument to another function in Python?

Higher Order Functions Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions. In the example below, a function greet is created which takes a function as an argument.

Can a Python function take another function as an argument?

In Python, just like a normal variable, we can pass a user-defined function as an argument to another function. A function that accepts another function as its parameter is called a Higher-order function.

What are the 4 types of arguments in Python?

5 Types of Arguments in Python Function Definition: positional arguments. arbitrary positional arguments. arbitrary keyword arguments.


2 Answers

Use the Callable type from typing. The Callable type is a generic so you can specify the signature of the function.

from typing import Callable

def high_order_math(a: float, b: float, func: Callable[[float, float], float]) -> float:
    return func(a, b)
like image 147
Samwise Avatar answered Nov 03 '22 01:11

Samwise


You've received a good answer, but inside the function body you can verify is the argument passed is callable:

def high_order_math(a: float, b: float, func):
    if not callable(func):
        raise TypeError
    else:
        print(a + b)
high_order_math(1, 2, lambda x, y: x + y) # works because it's callable
high_order_math(1, 2, 'hello') # raises error because it's not callable
like image 40
Nicolas Gervais Avatar answered Nov 02 '22 23:11

Nicolas Gervais