Print the docstring of a module in Python

avatar

Borislav Hadzhiev

Last updated: Sep 12, 2022

banner

Photo from Unsplash

Print the docstring of a module in Python #

Use the __doc__ attribute to print the docstring of a module, e.g. print(my_module.__doc__). If you need to print the docstring of the current module, use the __doc__ global variable, e.g. print(__doc__).

main.py
""" This module's docstring. """ import functools # functools.py - Tools for working with functions and callable objects print(functools.__doc__) # 👇️ This module's docstring. print(__doc__)

We used the __doc__ attribute to print the docstring of a file.

The __doc__ attribute returns the module's or function's documentation string or None if there isn't a docstring.

If you need to print the docstring of the current module, use the __doc__ global variable.

main.py
""" This module's docstring. """ # 👇️ This module's docstring. print(__doc__)

If you need to print the docstring of a built-in or third-party module, use the __doc__ attribute of the module.

main.py
import functools # functools.py - Tools for working with functions and callable objects print(functools.__doc__)

You can also access a specific method in the module and prints its docstring.

main.py
import functools # partial(func, *args, **keywords) - new function with partial application # of the given arguments and keywords. print(functools.partial.__doc__)

If you need to print the short documentation of a module in interactive mode, use the help() function.

main.py
import functools print(help(functools))

To print the short documentation of the current module in interactive mode, use the __name__ global variable.

main.py
""" This module's docstring. """ print(help(__name__))

You can also use the __doc__ attribute to print the docstring of a function.

main.py
def do_math(a, b): """Returns the sum of two numbers.""" # 👇️ print docstring from inside of a function print(do_math.__doc__) return a + b print(do_math.__doc__) # 👉️ Returns the sum of two numbers.

You can also use the __doc__ attribute if you need to print a function's docstring from inside of the function.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.