Python is known for its "batteries included" philosophy, offering a vast standard library and numerous built-in functions like print(), len(), and sorted(). However, remembering every parameter and behavior for these functions is impossible.
This guide explains how to access Python's built-in documentation directly from your code or interactive shell using the help() function and the __doc__ attribute.
Using the Interactive help() Function
The most direct way to read documentation is the built-in help() function. It invokes the interactive help system, which formats the text, arguments, and descriptions for readability.
Correct Usage
You must pass the function object itself to help(), not the result of calling the function.
help(print)Output (Truncated):
Help on built-in function print in module builtins:
print(...)
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: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
...Common Mistake: Calling the Function
If you add parentheses (), Python executes the function first and then asks for help on the return value.
help(print()) Output:
Help on NoneType object:
class NoneType(object)
| Methods defined here:
|
| __bool__(self, /)
| True if self else False
...Accessing Raw Docstrings via __doc__
Every Python object has a __doc__ dunder (double underscore) attribute. This attribute contains the raw documentation string (docstring). This is useful if you want to print the documentation programmatically without entering the interactive help mode.
doc_string = len.__doc__
print(doc_string)Output:
Return the number of items in a container.Understanding Function Signatures
When you access documentation, the most critical part is the Signature, i.e. the line defining the parameters.
Example signature from help(sorted):
sorted(iterable, /, *, key=None, reverse=False)
iterable: A required argument (e.g., a list)./: Arguments before this must be positional only.*: Arguments after this must be keyword arguments (named).reverse=False: An optional argument with a default value.
data = [3, 1, 2]
sorted_data = sorted(data, reverse=True)
print(sorted_data)Output:
[3, 2, 1]Conclusion
To effectively use Python's built-in functions:
- Use
help(function_name)in the interactive shell for a readable, detailed manual. - Use
print(function_name.__doc__)for a quick, programmatic check of what a function does. - Do not call the function inside
help(); pass the object directly.