python - -> 在 python 函数定义中

标签 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 中的作用?

最佳答案

这些是 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>

关于python - -> 在 python 函数定义中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15055929/

相关文章:

Python - 在从 json 对象中获取数据时,是否有一种优雅的方法来避免数十个 try/except block ?

python - 将 numpy.ndarray 值从字节转换为 float

python - 使用单词列表计算列表中的特定单词

python - 如何在 Python 中使用 exec() 换行?

python - 替代 python 文档

python - 从 Tumblr Api 获取视频 url

python - Django:客户端与流断开连接后清理redis连接

python - 如何查找和测量图像中的弧长

python - 计算 pandas df 中的非空值

python - 1行函数获取中间字母,语法错误