This short article will show you how to use the Python help() function to view the documentation (Docstring) for a Python module, class, or function.
Documenting Your Python Code with Docstrings
You can document your Python code with a special string called a docstring.
We’ve got a whole article on that here.
The short version of it is this: put a triple quoted string immediately after declaring a function, class, or module in Python:
""" Just like this """
…and you can later read from it using the help() function – allowing you to quickly look up what a function is intended to do without having to look at the code.
Using the help() Function to View Documentation/Docstrings
The help() function is built-in to Python and will display the docstring for a given object – this will not just print the docstring, but it will display the documentation for the function in an interactive shell similar to using the man command in the Linux shell.
To demonstrate, here’s a simple python function with a docstring documenting its functionality:
def multiplyNumbers(num1, num2): """ Multiplies two given numbers passed as parameters Parameters: num1 (integer) num2 (integer) Returns: The product of num1 and num2 """ return num1 * num2
And here’s how to use the help() function to view the docstring for the above:
The following text documentation will be displayed:
Multiplies two given numbers passed as parameters Parameters: num1 (integer) num2 (integer) Returns: The product of num1 and num2
Note that calling the help() function will halt the execution of your Python code until the q key is pressed to exit viewing the documentation/docstring.