iScrE4m iScrE4m - 1 year ago 66
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):

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__

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
, but it doesn't feel right because everywhere else we hint
. And importing types just for one annotation is also weird.
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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download