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

Viewed 319

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

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

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

Try this:

>>> def high_order_math(a, b, func):
...     if callable(func):
...         return func(a, b)
...     raise TypeError(f"{type(func)} is not a function or callable")
... 
>>> high_order_math(3, 4, lambda a,b: a+b)
7
Related