如何用参数logging一个方法?

如何使用Python的文档string来logging具有参数的方法?

编辑: 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 ... 

环境 :Python 2.7.1

根据我的经验, numpy文档string约定 (PEP257超集)是最广为stream传的遵循约定,也被工具支持,如Sphinx 。

一个例子:

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

由于docstrings是自由forms的,它实际上取决于你用什么来parsing代码来生成API文档。

我build议熟悉Sphinx标记 ,因为它被广泛使用,正在成为loggingPython项目的事实上的标准,部分原因是由于readthedocs.org的优秀服务。 将Sphinx文档中的示例作为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 ''' 

这个标记支持文档之间的交叉引用等等。 请注意,狮身人面像文件使用(例如) :py:attr:而你可以使用:attr:从源代码文件。

当然,还有其他工具来loggingAPI。 还有更经典的使用\param 命令的 Doxygen ,但这些并不是专门devise用来像Sphinx那样loggingPython代码的。

请注意,在这里有一个类似的答案 类似的问题 …

约定:

  • PEP 257文档string约定
  • PEP 287 reStructuredText Docstring格式

工具:

  • Epydoc:为Python自动生成API文档
  • sphinx.ext.autodoc – 包含来自docstrings的文档
  • PyCharm对docstrings有一些很好的支持

更新:自Python 3.5以来,您可以使用types提示 ,这是一种紧凑的机器可读语法:

 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这样的工具可以很容易地从中获益。

如果您打算使用狮身人面像来logging您的代码,它能够为您的参数生成格式良好的HTML文档,并带有“签名”function。 http://sphinx-doc.org/domains.html#signatures

python文档string是自由格式 ,你可以用任何你喜欢的方式logging它。

例子:

 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的工具也遵循特定的约定。

文档只在交互式环境中有用,例如Python shell。 当logging不会被交互使用的对象时(例如内部对象,框架callback),你也可以使用常规注释。 下面是一个用于悬挂缩进评论的样式的样式,每个都是自己的行,所以你知道这个评论适用于:

 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 

你不能用docstrings做这种事情。

主stream是,正如其他答案已经指出,可能与狮身人面像的方式,以便您可以使用狮身人面像后来生成那些奇特的文件。

也就是说,我个人会偶尔使用内联评论风格。

 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 

好处(如@ mark-horvath在另一评论中已经指出)是:

  • 最重要的是,参数和文档总是保持在一起,这带来了以下好处:
  • 减less打字(不需要重复variables名称)
  • 更改/删除variables时更易于维护。 重命名某个参数后,永远不会有一些孤儿参数doc段落。
  • 并更容易find缺less的评论。

现在,有人可能会认为这种风格看起来“丑陋”。 但是我会说“丑”是一个主观的词。 一个更为中性的方式是说,这种风格不是主stream,所以它可能看起来不太熟悉,因此不那么舒服。 再次,“舒适”也是一个主观的词汇。 但重要的是,上述所有的好处都是客观的。 你不能以标准的方式实现它们。

希望将来有一天会有一个文档生成器工具,它也可以使用这种内联风格。 这将推动采用。

PS:这个答案来源于我自己的喜好,只要我认为合适就使用内嵌评论。 我也使用相同的内联样式来logging字典 。