从函数获取文档字符串

问题:从函数获取文档字符串

我有以下功能:

def my_func():
    """My docstring is both funny and informative"""
    pass

如何获得文档字符串?

I have the following function:

def my_func():
    """My docstring is both funny and informative"""
    pass

How do I get access to the docstring?


回答 0

可以交互地显示

help(my_func)

或者从代码中,您可以使用

my_func.__doc__

Interactively, you can display it with

help(my_func)

Or from code you can retrieve it with

my_func.__doc__

回答 1

您也可以使用inspect.getdoc。它__doc__通过将制表符标准化为空格并向左移动文档主体以删除常见的前导空格来清理。

You can also use inspect.getdoc. It cleans up the __doc__ by normalizing tabs to spaces and left shifting the doc body to remove common leading spaces.


回答 2

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

my_func?

要么

?my_func

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

我避免使用

my_func??

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

On ipython or jupyter notebook, you can use all the above mentioned ways, but i go with

my_func?

or

?my_func

for quick summary of both method signature and docstring.

I avoid using

my_func??

(as commented by @rohan) for docstring and use it only to check the source code