什么->在 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 中没有可选的箭头"块,我在 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, as it is still undefined, - No matter what I put after the arrow (e.g.
2 < 1
), it doesn't affect the function behavior.
熟悉这种语法风格的人能解释一下吗?
Could anyone familiar with this syntax style 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.
相关文章