Print the docstring of a function in Python

avatar

Borislav Hadzhiev

Last updated: Sep 12, 2022

banner

Photo from Unsplash

Print the docstring of a function in Python #

Use the __doc__ attribute to print the docstring of a function, e.g. print(my_function.__doc__). The __doc__ attribute returns the function's documentation string.

main.py
def do_math(a, b): """Returns the sum of two numbers.""" print(do_math.__doc__) return a + b # Returns the sum of two numbers. # 25 print(do_math(10, 15)) # 👇️ Returns the sum of two numbers. print(do_math.__doc__)

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

The __doc__ attribute returns the function's documentation string or None if the function doesn't have a docstring.
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. # ------------------------------------- # 👇️ without docstring def example(): pass print(example.__doc__) # 👉️ None

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

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

main.py
def do_math(a, b): """Returns the sum of two numbers.""" return a + b # Help on function do_math in module __main__: # do_math(a, b) # Returns the sum of two numbers. # (END) print(help(do_math))

The __doc__ attribute can also be used to print the docstring of functions and methods you import.

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

The same approach can be used to print the docstring of an entire module you import.

main.py
import functools # functools.py - Tools for working with functions and callable objects print(functools.__doc__)
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.