从函数中获取docstring

Tei*_*ion 167 python

我有以下功能:

def my_func():
    """My docstring is both funny and informative"""
    pass
Run Code Online (Sandbox Code Playgroud)

如何访问docstring?

unw*_*ind 224

交互式地,您可以使用它进行显示

help(my_func)
Run Code Online (Sandbox Code Playgroud)

或者从代码中,您可以使用它来检索它

my_func.__doc__
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句:这种技术适用于内置函数以及模块和类(也可以使用对象测试 help() - 也可能有效)。这使您的 python shell 成为交互式帮助 shell! (4认同)
  • 在ipython提示符下,你可以做my_func ?? 它也会显示文档字符串. (3认同)
  • help(func) 提供可读输出,而 func.__doc__ 提供内联输出。感谢你的回答。 (2认同)

And*_*lke 74

您也可以使用inspect.getdoc.它通过将制表符规范化为空格来清除__doc__,并左移移文档主体以删除公共前导空格.

  • 它稍微清理了一下,但当文本需要在更宽的终端(例如 120 个字符)中打印时,您仍然会在原始位置获得换行符(例如 80 个字符)。有没有办法真正清理`__doc__`? (2认同)

Sam*_*nha 7

在ipython或jupyter笔记本上,您可以使用上述所有方法,但我同意

my_func?
Run Code Online (Sandbox Code Playgroud)

要么

?my_func
Run Code Online (Sandbox Code Playgroud)

快速概述方法签名和文档字符串。

我避免使用

my_func??
Run Code Online (Sandbox Code Playgroud)

(如@rohan所评论)以docstring,仅用于检查源代码