Getting the docstring from a function

Python

Python Problem Overview


I have the following function:

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

How do I get access to the docstring?

Python Solutions


Solution 1 - Python

Interactively, you can display it with

help(my_func)

Or from code you can retrieve it with

my_func.__doc__

Solution 2 - Python

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.

Solution 3 - Python

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

Solution 4 - Python

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('----')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTeifionView Question on Stackoverflow
Solution 1 - PythonunwindView Answer on Stackoverflow
Solution 2 - PythonAndrew DalkeView Answer on Stackoverflow
Solution 3 - PythonsssView Answer on Stackoverflow
Solution 4 - PythonSourav SarangiView Answer on Stackoverflow