問題描述
我最近在查看 Python 3.3 語法規(guī)范時(shí)發(fā)現(xiàn)了一些有趣的東西:
I've recently noticed something interesting when looking at Python 3.3 grammar specification:
funcdef: 'def' NAME parameters ['->' test] ':' suite
Python 2 中沒有可選的箭頭"塊,我在 Python 3 中找不到任何有關(guān)其含義的信息.事實(shí)證明這是正確的 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
我認(rèn)為這可能是某種前置條件語法,但是:
I thought that this might be some kind of a precondition syntax, but:
- 我無法在此處測(cè)試
x
,因?yàn)樗匀晃炊x, - 無論我在箭頭后面放什么(例如
2 < 1
),它都不會(huì)影響函數(shù)的行為.
- 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.
熟悉這種語法風(fēng)格的人能解釋一下嗎?
Could anyone familiar with this syntax style explain it?
推薦答案
這是一個(gè)函數(shù)注釋.
更詳細(xì)地說,Python 2.x 有文檔字符串,允許您將元數(shù)據(jù)字符串附加到各種類型的對(duì)象.這非常方便,因此 Python 3 通過允許您將元數(shù)據(jù)附加到描述其參數(shù)和返回值的函數(shù)來擴(kuò)展該功能.
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 建議了幾個(gè).一種非常方便的方法是允許您使用預(yù)期類型注釋參數(shù);然后很容易編寫一個(gè)裝飾器來驗(yàn)證注釋或?qū)?shù)強(qiáng)制為正確的類型.另一個(gè)是允許特定參數(shù)的文檔,而不是將其編碼到文檔字符串中.
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.
這篇關(guān)于什么->在 Python 函數(shù)定義中是什么意思?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!