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( )
?
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.
A function that accepts another function as its parameter is called a Higher-order function.
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().
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.
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)
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