Search code examples
pythonfunctionpython-typing

How to indicate that a function expects a function as a parameter, or returns a function, via function annotations?


You can use function annotations in python 3 to indicate the types of the parameters and return value, like so:

def myfunction(name: str, age: int) -> str:
    return name + str(age) #usefulfunction

But what if you were writing a function that expects a function as a parameter, or returns one?

I realize that you can write any valid expression in for the annotations, so I could write "function" as a string, but is that the best/only way of doing it? Is there nothing like the built-in types int/float/str/list/dict etc? I'm aware of callable, but I'm wondering if there's anything else.


Solution

  • There's no style defined for annotations. Either use callable, types.FunctionType or a string.

    PS: callable was not available in Python 3.0 and 3.1