How to Print the Docstring of a Module or Function in Python?

Estimated read time 2 min read

In Python, you can print the docstring of a module or function using the built-in help() function. The help() function takes an object as an argument and prints its docstring (if it has one) along with other helpful information.

To print the docstring of a module, you can simply pass the module name to the help() function. Here’s an example:

# Import the math module
import math

# Print the docstring of the math module
help(math)

Output:

Help on module math:

NAME
    math

MODULE REFERENCE
    https://docs.python.org/3/library/math.html

    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.

DESCRIPTION
    This module provides access to the mathematical functions
    defined by the C standard.

    [...]

In this example, we import the math module and pass it to the help() function. The resulting output includes the module name, a reference to the official documentation, a brief description of the module, and a list of its functions and constants.

To print the docstring of a function, you can pass the function name to the help() function. Here’s an example:

# Define a function with a docstring
def greet(name):
    """Greet someone by name."""
    print(f"Hello, {name}!")

# Print the docstring of the greet function
help(greet)

Output:

Help on function greet in module __main__:

greet(name)
    Greet someone by name.

In this example, we define a greet() function with a docstring, and then pass the function name to the help() function. The resulting output includes the function name, the docstring, and the function signature.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply