是什么->在Python函数定义中意味着什么?
我最近在查看 Python 3.3语法规范时发现一些有趣的东西. :
I've recently noticed something interesting when looking at Python 3.3 grammar specification:
funcdef: 'def' NAME parameters ['->' test] ':' suite
Python 2中没有可选的'arrow'块,我在Python 3中找不到有关其含义的任何信息.事实证明这是正确的Python,并已被解释器接受:
The optional 'arrow' block was absent in Python 2 and I couldn't find any information regarding its meaning in Python 3. It turns out this is correct Python and it's accepted by the interpreter:
def f(x) -> 123:
return x
我认为这可能是某种前提语法,但是:
I thought that this might be some kind of a precondition syntax, but:
- 我无法在此处测试
x
,因为它仍未定义, - 无论我在箭头后面加上什么(例如
2 < 1
),它都不会影响功能行为.
- I cannot test
x
here, at it is still undefined, - No matter what I put after the arrow (e.g.
2 < 1
), it doesn't affect the function behaviour.
习惯使用这种语法的人可以解释它吗?
Could anyone accustomed with this syntax explain it?
这是一个功能注释.
更详细地讲,Python 2.x具有文档字符串,使您可以将元数据字符串附加到各种类型的对象.这非常方便,因此Python 3通过允许您将元数据附加到描述其参数和返回值的函数来扩展该功能.
In more detail, Python 2.x has docstrings, which allow you to attach a metadata string to various types of object. This is amazingly handy, so Python 3 extends the feature by allowing you to attach metadata to functions describing their parameters and return values.
没有预想的用例,但PEP建议了几个.一种非常方便的方法是允许您使用期望的类型来注释参数.这样就很容易编写一个装饰器来验证注释或将参数强制为正确的类型.另一个是允许使用特定于参数的文档,而不是将其编码为文档字符串.
There's no preconceived use case, but the PEP suggests several. One very handy one is to allow you to annotate parameters with their expected types; it would then be easy to write a decorator that verifies the annotations or coerces the arguments to the right type. Another is to allow parameter-specific documentation instead of encoding it into the docstring.