有没有办法让文档字符串与它们记录的函数分开?

hwi*_*ers 4 python docstring

我正在研究一个具有许多小函数的模块,但其文档字符串往往很长.文档字符串使得模块工作变得烦人,因为我必须不断滚动一个长文档字符串来查找一些实际代码.

有没有办法让文档字符串与它们记录的函数分开?我真的希望能够在远离代码的文件末尾指定文档字符串,或者甚至更好地在单独的文件中指定.

Gre*_*ill 10

函数的docstring可用作特殊属性__doc__.

>>> def f(x):
...     "return the square of x"
...     return x * x
>>> f.__doc__
'return the square of x'
>>> help(f)
(help page with appropriate docstring)
>>> f.__doc__ = "Return the argument squared"
>>> help(f)
(help page with new docstring)
Run Code Online (Sandbox Code Playgroud)

无论如何,这证明了这项技术.在实践中,您可以:

def f(x):
    return x * x

f.__doc__ = """
Return the square of the function argument.

Arguments: x - number to square

Return value: x squared

Exceptions: none

Global variables used: none

Side effects: none

Limitations: none
"""
Run Code Online (Sandbox Code Playgroud)

......或者你想要放在文档字符串中的任何内容.