正如此处其他答案所指出的那样,主流可能是Sphinx方法,以便您以后可以使用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
好处(如@ mark-horvath在另一条评论中已经指出的)是:
- 最重要的是,参数及其文档始终保持在一起,这带来了以下好处:
- 更少的输入(无需重复变量名)
- 更改/删除变量时更容易维护。重命名某些参数后,将永远不会有任何孤立参数doc段落。
- 更容易找到遗漏的评论。
现在,有些人可能认为这种样式看起来“丑陋”。但是我会说“丑陋”是一个主观的词。更为中性的说法是,这种风格不是主流,因此您看起来不太熟悉,因此不太舒适。同样,“舒适”也是一个主观词。但是关键是,上述所有好处都是客观的。如果遵循标准方法,则无法实现它们。
希望在将来的某一天,将有一个文档生成器工具也可以使用这种内联样式。这将推动采用。
PS:这个答案来自我自己的偏爱,即在我认为合适时使用内联注释。我也使用相同的内联样式来记录字典。