Search code examples
pythonfunctiontype-hinting

What is the data type of a parameter that is a function?


When I create a function, I often specify the data types of its arguments, for example:

def my_func(name: str, surname: str) -> str:
       full_name = name + surname
       return full_name

but if an argument of a function is another function, what is its data type?

I tried to do this:

def my_func_2(func: function) -> str: 
    return func()

but I get

NameError: name function is not defined


Solution

  • You should find something useful in module typing.

    def my_func_2(func: typing.Callable) -> str: 
    

    The cleanest solution is to import only Callable from the module, to prevent the function's prototype to be too long.

    from typing import Callable
    
    def my_func_2(func: Callable) -> str: