iScrE4m iScrE4m - 3 months ago 9
Python Question

How to properly function annotate function-argument

I want my function to be annotated that it takes another function as an argument. At first I thought that this is going to work just fine:

def my_function(func_argument: function):
pass


however function is unresolved reference. I looked through builtins and it is indeed not there, unlike str, int and others I typically use. However, it has to be somewhere, because:

>>> def my_function():
... pass
...
>>> x = my_function
>>> type(x)
<class 'function'>
>>> type(x).__name__
'function'


Where is the function class defined, why isn't it in builtins? Is my original try supposed to be the correct solution? For now I went with annotating it with
types.FunctionType
, but it doesn't feel right because everywhere else we hint
str
not
types.StringType
. And importing types just for one annotation is also weird.
typing
library also doesn't have anything it that would help me replace this.

Also, how would FunctionType work with a type annotation enforcing library (I saw few of those flying around)

Answer

Why not use Callable:

Frameworks expecting callback functions of specific signatures might be type hinted using Callable[[Arg1Type, Arg2Type], ReturnType]


from typing import Callable

def my_function(func_argument: Callable[..., ReturnType]): # replace ReturnType with return type of func_argument
    pass