273

I have the following function:

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

How do I get access to the docstring?

1
  • 19
    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. Commented Apr 3, 2009 at 14:16

5 Answers 5

375

Interactively, you can display it with:

help(my_func)

Or from code you can retrieve it with (surround it with print(.) to get a formatted output):

my_func.__doc__
Sign up to request clarification or add additional context in comments.

4 Comments

BTW: This technique works with builtin functions as well as modules and classes (test help() with objects too - might also work). This makes your python shell an interactive help shell!
On the ipython prompt, you can do my_func?? and it would show the docstring as well.
help(func) gives a readable output while func.__doc__ gives a inline output. Thanks for the answer.
@Mr.UnnormalizedPosterior try print(func.__doc__); I find it more useful while in the CLI, easy to go back to the func's signature when needed.
110

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 Comments

It cleans it up a bit, but you still get newlines at the original e.g. 80 characters, when the text needs to be printed in a terminal that is wider, e.g. 120 characters. Is there a way to really clean up the __doc__ ?
@xApple The docstring can generally contain lists or blocks of code - things that you want to keep formatted by newlines. If you still want to remove all the newlines in the string, then just remove them, using the str.replace method.
13

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

Comments

1

The ast module can be used to parse a file with python code and build an "Abstract Syntax Tree" for it. Then one can "walk" that to extract docstrings, and process/present them as desired

import ast
import sys
f = open(sys.argv[1], "r") #filename input
module = ast.parse(f.read())
class_definitions = [node for node in module.body if isinstance(node, ast.ClassDef)]
method_definitions = []
for class_def in class_definitions:
        print(class_def.name)
        print(ast.get_docstring(class_def))
        function_definitions = [node for node in class_def.body if isinstance(node, ast.FunctionDef)]
        for f in function_definitions:
                print('\t---')
                print('\t'+f.name)
                print('\t---')
                print('\t'+'\t'.join(ast.get_docstring(f).splitlines(True)))
        print('----')

1 Comment

This answer uses the ast module to parse a text file containing python source code into and abstract syntax tree. The purpose seems to be to extract the doc strings from the file. All the other answers require the code to be executed in order to retrieve the document string, which could be unwise or undesirable. It is a very valid answer, yet would be improved with an explanation. The original question did not indicate whether the docstring was required at runtime or not.
1

If inside a class you can also do something like this:

import sys

class A(object):
    """ A class """

    def func_values(self):
        fn_name = sys._getframe(1).f_code.co_name
        fn_doc  = eval(f"self.{fn_name}.__doc__") or 'N/A'
        return (fn_name, fn_doc)

    def func_A(self):
        # handle NO docstring
        name, docstring = self.func_values()
        print(name, '=>', docstring)

    def func_B(self):
        """ This is function B which has a docstring """
        name, docstring = self.func_values()
        print(name, "=>", docstring)

a = A()
a.func_A()
a.func_B()

2 Comments

Accessing the docstring using eval seems unnecessarily complicated. self.func_A.__doc__ works equally well. At least when you call it inside a method, its own name is always known. Of course you cannot just copy-paste the code...
@UweGeuder but you don't know in which function you are .. (self.func_A or self.func_B - the function name is dynamic ... this is why the eval

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.