Python help() Function
Description
The help() function is used to display the documentation string of the specified module, class, method, function, variables, etc.
Syntax
help()
Parameters
- object: Any object, such as module, class, method, function, variables, etc.
Return Value
This function returns the help information of the object.
Example
The following example demonstrates how to use the help() function:
# Display the help information for the built-in module 'sys'
import sys
help(sys)
# Display the help information for the built-in function 'len'
help(len)
# Display the help information for the list type
help(list)
# Display the help information for the method 'append' of the list
mylist = [1, 2, 3]
help(mylist.append)
Example 2: Interactive Mode
In Python's interactive mode, you can directly enter help(object) to view documentation:
>>> help(print)
Help on built-in function print in module builtins:
print(value, ..., sep=' ', end='n', file=sys.stdout, flush=False)
Prints the values to a stream or to sys.stdout by default.
Optional keyword arguments file, sep, end, and flush differ slightly
from their keyword arguments, as in Python 2.
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
Example 3: Custom Function Documentation
If you have a custom function with a docstring, help() will display it:
def greet(name):
"""
This function prints a greeting message.
Parameters:
name (str): The name of the person to greet
Returns:
None
"""
print(f"Hello, {name}!")
# View the help information for the custom function
help(greet)
Output:
Help on function greet in module __main__:
greet(name)
This function prints a greeting message.
Parameters:
name (str): The name of the person to greet
Returns:
None
Notes
- If help() is called without any arguments, it enters the interactive help mode where you can browse documentation for various modules and functions.
- The help() function internally calls the __doc__ attribute of the object to get the documentation string.
- For built-in types and functions, help() displays information from Python's built-in documentation.
YouTip