What does -> mean in Python function definitions?

https://stackoverflow.com/questions/14379753/what-does-mean-in-python-function-definitions

https://www.python.org/dev/peps/pep-3107/

 

Wow, I missed quite a broad area of knowledge - not only return value annotations, but also parameter annotations. Thank you very much :)

And the __annotations__ attribute is a dictionary. The key return is the one used to retrieve the value after the arrow.

 

 

>>> def kinetic_energy(m:'in KG', v:'in M/S')->'Joules': 
...    return 1/2*m*v**2
... 
>>> kinetic_energy.__annotations__
{'return': 'Joules', 'v': 'in M/S', 'm': 'in KG'}


>>> rd={'type':float,'units':'Joules','docstring':'Given mass and velocity returns kinetic energy in Joules'}
>>> def f()->rd:
...    pass
>>> f.__annotations__['return']['type']
<class 'float'>
>>> f.__annotations__['return']['units']
'Joules'
>>> f.__annotations__['return']['docstring']
'Given mass and velocity returns kinetic energy in Joules'

-> is introduced in python3.

In simpler words, the content after the -> denotes the return type of the function. The return type is optional.

 

posted on 2021-07-23 14:17  cdekelon  阅读(41)  评论(0编辑  收藏  举报

导航