Print the documentation of a module in Python

avatar

Borislav Hadzhiev

Last updated: Sep 12, 2022

banner

Photo from Unsplash

Print the documentation of a module in Python #

Use the __doc__ attribute to print the documentation of a module, e.g. print(functools.__doc__). If you need to print the documentation 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__) # partial(func, *args, **keywords) - new function with partial application # of the given arguments and keywords. print(functools.partial.__doc__)

We used the __doc__ attribute to print the documentation of a module.

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 documentation of a built-in or third-party module, access the __doc__ attribute on 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 documentation string.

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 # Help on module functools: # NAME # functools - functools.py - Tools for working with functions and callable objects # MODULE REFERENCE # https://docs.python.org/3.10/library/functools.html # ... 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. """ # Help on module __main__: # NAME # __main__ - This module's docstring. # DATA # __annotations__ = {} # FILE # /home/borislav/Desktop/bobbyhadz_python/main.py 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.