Python函數定義中的 - >意思是什麼?


Answers

這些是PEP 3107中涵蓋的功能註釋。 具體來說, ->標記返回函數註釋。

例子:

>>> 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'}

註釋是詞典,所以你可以這樣做:

>>> '{:,} {}'.format(kinetic_energy(20,3000),
      kinetic_energy.__annotations__['return'])
'90,000,000.0 Joules'

你也可以有一個Python數據結構,而不僅僅是一個字符串:

>>> 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'

或者,您可以使用函數屬性來驗證調用的值:

def validate(func, locals):
    for var, test in func.__annotations__.items():
        value = locals[var]
        try: 
            pr=test.__name__+': '+test.__docstring__
        except AttributeError:
            pr=test.__name__   
        msg = '{}=={}; Test: {}'.format(var, value, pr)
        assert test(value), msg

def between(lo, hi):
    def _between(x):
            return lo <= x <= hi
    _between.__docstring__='must be between {} and {}'.format(lo,hi)       
    return _between

def f(x: between(3,10), y:lambda _y: isinstance(_y,int)):
    validate(f, locals())
    print(x,y)

打印

>>> f(2,2) 
AssertionError: x==2; Test: _between: must be between 3 and 10
>>> f(3,2.1)
AssertionError: y==2.1; Test: <lambda>
Question

我最近注意到Python 3.3語法規範時有一些有趣的地方:

funcdef: 'def' NAME parameters ['->' test] ':' suite

Python 2中缺少可選的“箭頭”塊,我無法在Python 3中找到任何有關其含義的信息。事實證明,這是正確的Python,它已被解釋器接受:

def f(x) -> 123:
    return x

我認為這可能是某種先決條件語法,但是:

  • 我不能在這裡測試x ,它仍然是未定義的,
  • 無論我放在箭頭後面(例如2 < 1 ),它都不會影響功能行為。

任何習慣於這種語法的人都可以解釋它嗎?




Links