問題描述
函數注釋:PEP-3107
我遇到了一段演示 Python3 函數注釋的代碼片段.這個概念很簡單,但我想不出為什么這些是在 Python3 中實現的,或者它們有什么好的用途.也許SO可以啟發我?
I ran across a snippet of code demonstrating Python3's function annotations. The concept is simple but I can't think of why these were implemented in Python3 or any good uses for them. Perhaps SO can enlighten me?
它是如何工作的:
def foo(a: 'x', b: 5 + 6, c: list) -> max(2, 9):
... function body ...
參數后冒號后面的所有內容都是注解",->
后面的信息是函數返回值的注解.
Everything following the colon after an argument is an 'annotation', and the information following the ->
is an annotation for the function's return value.
foo.func_annotations 會返回一個字典:
foo.func_annotations would return a dictionary:
{'a': 'x',
'b': 11,
'c': list,
'return': 9}
提供這個有什么意義?
推薦答案
我覺得這真的很棒.
來自學術背景,我可以告訴您,注釋已證明它們對于為 Java 等語言啟用智能靜態分析器非常寶貴.例如,您可以定義諸如狀態限制、允許訪問的線程、架構限制等語義,并且有相當多的工具可以讀取并處理它們,以提供超出您從編譯器獲得的保證的保證.你甚至可以編寫檢查前置條件/??后置條件的東西.
Coming from an academic background, I can tell you that annotations have proved themselves invaluable for enabling smart static analyzers for languages like Java. For instance, you could define semantics like state restrictions, threads that are allowed to access, architecture limitations, etc., and there are quite a few tools that can then read these and process them to provide assurances beyond what you get from the compilers. You could even write things that check preconditions/postconditions.
我覺得在 Python 中尤其需要這樣的東西,因為它的類型較弱,但實際上沒有任何結構可以讓這種簡單直接成為官方語法的一部分.
I feel something like this is especially needed in Python because of its weaker typing, but there were really no constructs that made this straightforward and part of the official syntax.
除了保證之外,注釋還有其他用途.我可以看到如何將基于 Java 的工具應用到 Python.例如,我有一個工具可以讓您為方法分配特殊警告,并在您調用它們時提示您應該閱讀它們的文檔(例如,假設您有一個不能以負值調用的方法,但它是從名稱上看不直觀).使用注釋,我可以在技術上為 Python 編寫類似的東西.同樣的,如果有官方的語法,也可以寫出一個基于標簽組織大類中方法的工具.
There are other uses for annotations beyond assurance. I can see how I could apply my Java-based tools to Python. For instance, I have a tool that lets you assign special warnings to methods, and gives you indications when you call them that you should read their documentation (E.g., imagine you have a method that must not be invoked with a negative value, but it's not intuitive from the name). With annotations, I could technically write something like this for Python. Similarly, a tool that organizes methods in a large class based on tags can be written if there is an official syntax.
這篇關于Python3 的“函數注釋"有什么好的用途?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!