python docstrings in python

In Python, docstrings are used for documenting modules, classes, functions and methods. They are used to provide a summary of a function and explain its usage, arguments and other important details.

Here is an example of a function with a docstring:

main.py
def my_function(arg1, arg2):
    """
    This is a docstring for my_function.

    Args:
        arg1 (int): This is argument 1. It should be an integer.
        arg2 (str): This is argument 2. It should be a string.

    Returns:
        bool: This function returns a boolean value.
    """
    # Function code goes here
322 chars
13 lines

As you can see, we enclose the docstring in triple quotes (""") at the beginning of the function. Inside the docstring, we provide a summary of what the function does, what arguments it takes and what it returns.

You can access the docstring of a function using the __doc__ attribute:

main.py
print(my_function.__doc__)
27 chars
2 lines

This will output the docstring of the my_function function.

You can also use the help() function to display the docstring of a function:

main.py
help(my_function)
18 chars
2 lines

This will display the docstring of the my_function function along with some additional information about the function.

related categories

gistlibby LogSnag