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
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.
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.
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.
5 Types of Arguments in Python Function Definition: positional arguments. arbitrary positional arguments. arbitrary keyword arguments.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With