- >在python函数定义中

时间:2013-02-24 19:53:26

标签: python python-3.x

我正在查看python 3.3 grammar,并在其中注意到这一行:

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

这意味着 - >在定义函数时是一个有效的符号,但我无法在网上找到它的内容,而且据我所知,它被忽略了。例如,我可以编写执行此操作的代码:

def a() -> True: pass

def a() -> 5 == 3:
    return 8

都是有效的陈述,但似乎没有做任何事情。

有人能告诉我python中的->语法吗?

1 个答案:

答案 0 :(得分:0)

这些是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(kenetic_energy(20,3000),
      kenetic_energy.__annotations__['return'])
'90,000,000.0 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>