2009-01-28 42 views

回答

17

函數註釋並非針對特定用途,它們可用於任何事情。

可以編寫工具來從註釋中提取信息並執行任何您想要的操作,包括檢查類型或生成文檔。但是python本身並沒有對信息做任何事情。您可以使用一個完全不同的目的,即提供一個將在參數上調用的函數或聲明可能的返回值的字符串。

註釋可以是任何對象:

def somefunc(param1: "string annotation", 
      param2: 151631, 
      param3: any_object): -> "some information here": 

,您可以使用檢索對象:

  • 提供輸入信息 :由PEP提供

    print (somefunc.func_annotations) 
    {'param1': "string annotation", 
    'param2': 151631, 
    'param3': <object any_object>, 
    'return': "some information here"} 
    

    使用情況的建議

    • 類型檢查
    • 讓我們的IDE顯示函數需要什麼類型的,並返回
    • 函數重載/通用功能
    • 外語橋樑
    • 適應
    • 謂詞邏輯功能
    • 數據庫的查詢映射
    • RPC參數封送
  • 參數和返回其他信息
    • 文檔值

由於功能註釋語法是太新,但真的不用於任何生產工具。

我建議使用其他方法來記錄它。我用epydoc的生成我的文檔,並且它可以從文檔字符串讀取參數輸入信息:

def x_intercept(m, b): 
    """ 
    Return the x intercept of the line M{y=m*x+b}. The X{x intercept} 
    of a line is the point at which it crosses the x axis (M{y=0}). 

    This function can be used in conjuction with L{z_transform} to 
    find an arbitrary function's zeros. 

    @type m: number 
    @param m: The slope of the line. 
    @type b: number 
    @param b: The y intercept of the line. The X{y intercept} of a 
       line is the point at which it crosses the y axis (M{x=0}). 
    @rtype: number 
    @return: the x intercept of the line M{y=m*x+b}. 
    """ 
    return -b/m 

這個例子來自epydoc's website。它可以生成各種格式的文檔,並且可以從您的類和通話配置文件生成良好的圖形。

+0

您可以詳細說明在哪個版本的Python中添加了此語法嗎? – 2009-01-28 10:57:44

7

如果您使用epydoc來生成API文檔,您有三種選擇。

  • Epytext。

  • ReStructuredText,RST。

  • JavaDoc符號,看起來有點像epytext。

我建議RST,因爲它sphinx非常適用於產生整體的文檔套件,包括API引用。 RST標記定義爲here。您可以指定的各種epydoc字段定義爲here

例子。

def someFunction(arg1, arg2): 
    """Returns the average of *two* (and only two) arguments. 

    :param arg1: a numeric value 
    :type arg1: **any** numeric type 

    :param arg2: another numeric value 
    :type arg2: **any** numeric type 

    :return: mid-point (or arithmetic mean) between two values 
    :rtype: numeric type compatible with the args. 
    """ 
    return (arg1+arg2)/2 
2

的Python 3.5正式typing

https://docs.python.org/3/library/typing.html

此更新可種語言的實際組成部分。

實施例:

#!/usr/bin/env python3 

from typing import List 

def f(x: int, ys: List[float]) -> str: 
    return "abc" 

# Good. 
f(1, [2.0, 3.0]) 

# Bad. 
f("abc", {}) # line 12 

x = 1 
x = "a" # line 15 

y = [] # type: List[int] 
y.append("a") # line 18 

此代碼正常運行:Python的3.5默認情況下不執行打字。

但然而,可以通過靜態棉短絨用於diagnoze問題,如:

sudo pip3 install mypy 
mypy a.py 

給出:

a.py:12: error: Argument 1 to "f" has incompatible type "str"; expected "int" 
a.py:12: error: Argument 2 to "f" has incompatible type Dict[<nothing>, <nothing>]; expected List[float] 
a.py:15: error: Incompatible types in assignment (expression has type "str", variable has type "int") 
a.py:18: error: Argument 1 to "append" of "list" has incompatible type "str"; expected "int" 

現有的像Pycharm的靜態分析儀已經可以解析獅身人面像的文檔類型,但這種語言更新提供了一個官方規範的方式,可能會佔上風。

相關問題