Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 268
temporary_user_name Avatar asked Dec 20 '13 02:12

temporary_user_name


People also ask

What is __ annotations __ in Python?

__annotations__ Quirks __annotations__ the object will create a new empty dict that it will store and return as its annotations. Deleting the annotations on a function before it has lazily created its annotations dict will throw an AttributeError ; using del fn.

What is a function annotation?

Function annotations, both for parameters and return values, are completely optional. Function annotations are nothing more than a way of associating arbitrary Python expressions with various parts of a function at compile-time.


2 Answers

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

like image 151
JBernardo Avatar answered Sep 20 '22 01:09

JBernardo


Very interesting... I've never even heard of function annotations in Python 3. The following code in the interpreter suggests you might use function in place of str and int. Just my two cents.

>>> a = lambda x: x*2
>>> type(a)
<class 'function'>
like image 40
SimonT Avatar answered Sep 20 '22 01:09

SimonT