206
votes

I have the following function:

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

How do I get access to the docstring?

3
Note that running Python with -OO strips out docstrings. If you intend to distribute your code to others, keep in mind that they may run it that way. It will make those people really really unhappy if your code relies on docstrings, but doesn't catch the case where they don't exist. - DNS

3 Answers

275
votes

Interactively, you can display it with

help(my_func)

Or from code you can retrieve it with

my_func.__doc__
88
votes

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.

10
votes

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