How to get help on a function in Python
Published on Aug. 22, 2023, 12:15 p.m.
To get help on a function in Python, you can use the built-in help()
function or the .__doc__
attribute on the function object.
Here’s an example using the help()
function:
def my_function():
"""This is a docstring that explains what the function does."""
return "Hello, world!"
help(my_function)
Output:
Help on function my_function in module __main__:
my_function()
This is a docstring that explains what the function does.
As you can see, the help()
function prints the docstring for the specified function. You can also use the __doc__
attribute on the function object to access the docstring directly:
def my_function():
"""This is a docstring that explains what the function does."""
return "Hello, world!"
print(my_function.__doc__)
Output:
This is a docstring that explains what the function does.
Note that the docstring should be enclosed in triple quotes at the beginning of the function definition, and is usually used to provide a brief description of what the function does, as well as any arguments it takes and what it returns.
What is help function
The help()
function in Python is used to display the documentation for a specified module, function, class, or object. It can be used interactively from within the Python interpreter, as well as in scripts and modules. When called with an object or module as an argument, help()
prints a summary of the object’s purpose and usage instructions, based on its documentation string (or “docstring” for short).
For example, you can use help()
to get help on a built-in function like print()
:
help(print)
This will display the help documentation for the print()
function, including its parameters, usage instructions, and examples.
This will display the docstring for the my_function()
function.