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.
__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.
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.
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
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'>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With