2012-02-08 39 views
77

如何使用Python的文檔字符串來記錄具有參數的方法?如何使用參數記錄方法?

編輯: PEP 257給出了這樣的例子:

def complex(real=0.0, imag=0.0): 
    """Form a complex number. 

    Keyword arguments: 
    real -- the real part (default 0.0) 
    imag -- the imaginary part (default 0.0) 

    """ 
    if imag == 0.0 and real == 0.0: return complex_zero 
    ... 

這是大多數Python開發者使用的慣例?

Keyword arguments: 
<parameter name> -- Definition (default value if any) 

我期待更多的東西一點點正式比如

def complex(real=0.0, imag=0.0): 
    """Form a complex number. 

    @param: real The real part (default 0.0) 
    @param: imag The imaginary part (default 0.0) 

    """ 
    if imag == 0.0 and real == 0.0: return complex_zero 
    ... 

Environement:Python的2.7.1

+0

你讀過PEP 257? http://www.python.org/dev/peps/pep-0257/ – NPE 2012-02-08 14:47:37

+1

這裏有幾個「標準」,但實際的方法,特別是如果你喜歡正式的東西,我會建議[獅身人面像](http:///pythonhosted.org/an_example_pypi_project/sphinx.html)。它在[Pycharm](https://www.jetbrains.com/pycharm/)中的集成使生成結構良好的文檔字符串非常輕鬆。恕我直言 – jojo 2014-06-24 09:24:55

回答

57

根據我的經驗,numpy docstring conventions(PEP257超集)是最廣泛流傳其次慣例,它們也通過工具的支持,如Sphinx

一個例子:

Parameters 
---------- 
x : type 
    Description of parameter `x`. 
+1

這更接近我的預期。不幸的是,我選擇了普通的PEP 257並添加了我自己的約定(以放棄自動生成的HTML/PDF文檔爲代價)。 但是,下次我會選擇這個解決方案。謝謝。 – 2012-04-11 05:51:05

+5

當我嘗試處理你建議的文檔字符串時,獅身人面像抱怨'嚴重:意外的章節標題' - 你知道有什麼方法讓獅身人面像更快樂嗎? – 2014-01-21 04:54:31

+0

@BrandonRhodes這個鏈接是關於在Sphinx中使用這些約定的討論:https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt – Halst 2015-05-07 09:00:58

25

約定:

工具:


更新:因爲Python 3.5,你可以使用type hints這是一個結構緊湊,機器可讀的語法:

from typing import Dict, Union 

def foo(i: int, d: Dict[str, Union[str, int]]) -> int: 
    """ 
    Explanation: this function takes two arguments: `i` and `d`. 
    `i` is annotated simply as `int`. `d` is a dictionary with `str` keys 
    and values that can be either `str` or `int`. 

    The return type is `int`. 

    """ 

這句法的主要優點是,它是由語言定義的,它是明確的,所以像PyCharm工具,可以輕鬆地從它的優勢。

+10

雖然這個答案現在是最有利的,但上面的PEP都沒有提供一個約定來指定方法的參數類型。 – koriander 2013-09-23 07:32:53

+0

pep287的+1鏈接 – spinus 2014-06-09 13:57:24

7

python doc字符串是自由格式,您可以用任何您喜歡的方式記錄它。

例子:

def mymethod(self, foo, bars): 
    """ 
    Does neat stuff! 
    Parameters: 
     foo - a foo of type FooType to bar with. 
     bars - The list of bars 
    """ 

現在,有一些約定,但是Python不強制任何人。有些項目有自己的約定。一些使用docstrings的工具也遵循特定的約定。

3

Docstrings僅在交互式環境中有用,例如, Python shell。當記錄不會交互使用的對象時(例如內部對象,框架回調),您不妨使用常規註釋。這是一種風格我用掛項目縮進的意見,每個對自己行,所以你知道註釋適用於:

def Recomputate \ 
    (
    TheRotaryGyrator, 
     # the rotary gyrator to operate on 
    Computrons, 
     # the computrons to perform the recomputation with 
    Forthwith, 
     # whether to recomputate forthwith or at one's leisure 
) : 
    # recomputates the specified rotary gyrator with 
    # the desired computrons. 
    ... 
#end Recomputate 

你不能做這樣的事情有文檔字符串。

+31

哦,這個看起來很醜。 – 2012-02-09 15:02:35

+1

醜陋的是嗎?有趣的想法...也是。 – David 2014-11-13 09:30:55

+2

對於變量的內聯註釋非常合理,輸入較少(不需要重複變量名稱),更改/移除變量時更易於維護......更容易找到缺少的註釋。將它與簽名下的正確文檔字符串結合使用。 +1 – 2015-04-24 00:07:50

2

其他答案在這裏已經指出,可能與Sphinx way一起使用,以便您可以使用Sphinx在稍後生成那些奇特的文檔。

這就是說,我個人會偶爾使用內聯評論風格。

def complex( # Form a complex number 
     real=0.0, # the real part (default 0.0) 
     imag=0.0 # the imaginary part (default 0.0) 
     ): # Returns a complex number. 
    """Form a complex number. 

    I may still use the mainstream docstring notation, 
    if I foresee a need to use some other tools 
    to generate an HTML online doc later 
    """ 
    if imag == 0.0 and real == 0.0: 
     return complex_zero 
    other_code() 

這裏再舉一個例子,有一些微小的細節記錄在線:

def foo( # Note that how I use the parenthesis rather than backslash "\" 
      # to natually break the function definition into multiple lines. 
     a_very_long_parameter_name, 
      # The "inline" text does not really have to be at same line, 
      # when your parameter name is very long. 
      # Besides, you can use this way to have multiple lines doc too. 
      # The one extra level indentation here natually matches the 
      # original Python indentation style. 
      # 
      # This parameter represents blah blah 
      # blah blah 
      # blah blah 
     param_b, # Some description about parameter B. 
      # Some more description about parameter B. 
      # As you probably noticed, the vertical alignment of pound sign 
      # is less a concern IMHO, as long as your docs are intuitively 
      # readable. 
     last_param, # As a side note, you can use an optional comma for 
        # your last parameter, as you can do in multi-line list 
        # or dict declaration. 
     ): # So this ending parenthesis occupying its own line provides a 
      # perfect chance to use inline doc to document the return value, 
      # despite of its unhappy face appearance. :) 
    pass 

的好處(如@標記霍瓦特已在其它評論指出)是:

  • 最重要的是,參數和他們的文檔始終保持在一起,這帶來以下好處:
  • 減少打字(無需重複變量名稱)
  • 更改/刪除變量時更易於維護。重命名某些參數後,絕不會有一些孤兒參數doc段落。
  • 和更容易找到缺少的評論。

現在,有人可能會認爲這種風格看起來很「醜陋」。但我會說「醜」是一個主觀詞。更加中性的方式是說,這種風格不是主流,所以它可能看起來不太熟悉,因此不太舒服。再次,「舒適」也是一個主觀詞彙。但重要的是,上述所有的好處都是客觀的。你不能以標準的方式實現它們。

希望未來有一天,會有一個文檔生成器工具,它也可以使用這種內聯樣式。這將推動採用。

PS:這個答案來源於我自己喜歡的每當我認爲合適時使用內嵌評論。我也使用same inline style to document a dictionary

32

由於docstrings是自由形式的,它實際上取決於你用什麼來解析代碼來生成API文檔。

我會建議得到熟悉Sphinx markup,因爲它被廣泛應用,併成爲記錄Python項目,部分是因爲出色的readthedocs.org服務的事實標準。爲了paraphrase an example從獅身人面像的文件爲Python代碼片段:

def send_message(sender, recipient, message_body, priority=1): 
    ''' 
    Send a message to a recipient 

    :param str sender: The person sending the message 
    :param str recipient: The recipient of the message 
    :param str message_body: The body of the message 
    :param priority: The priority of the message, can be a number 1-5 
    :type priority: integer or None 
    :return: the message id 
    :rtype: int 
    :raises ValueError: if the message_body exceeds 160 characters 
    :raises TypeError: if the message_body is not a basestring 
    ''' 

此標記支持文件多間cross-referencing。請注意,Sphinx文檔使用(例如):py:attr:,而您可以在從源代碼記錄時僅使用:attr:

當然,還有其他工具可以記錄API。還有更經典的Doxygen,它使用\paramcommands,但這些並不是專門設計用來像Sphinx那樣記錄Python代碼的。

注意,有一個similar question在這裏similar answer ...

+1

默認情況下,這是PyCharm的評論自動生成使用的樣式 – 2017-09-01 16:31:22

相關問題