The help() built-in function invokes Python's built-in pydoc documentation system to display formatted reference manuals for modules, classes, functions, and keywords.
Built-in Help & Dynamic Introspection: Calling help() with an object displays its signature, docstring, and method hierarchy. Calling it without arguments starts an interactive terminal session. To list available attribute names programmatically, see dir() or vars(). For writing clear module and class documentation, review docstrings, or inspect object types with type() and repr().
The help() function accepts an optional object or string parameter:
# Formal syntax of built-in help()
help([object])
| Parameter | Type | Default | Description & Operational Rule |
|---|---|---|---|
object |
Any or str |
Optional | Object, class, function, module reference, or topic string to inspect. |
| Return | None |
N/A | Prints formatted manual text to standard output and returns None. |
| No Argument | Interactive REPL | N/A | Starts an interactive terminal session at the help> prompt. |
Pass function identifiers, methods, classes, or modules to print their signatures and documentation:
# 1. Direct object inspection (functions, methods, and classes)
# Inspecting built-in function signature and parameters
help(print)
# Inspecting standard string method
help(str.replace)Terminal Output:
Help on built-in function print in module builtins:
print(*args, sep=' ', end='\n', file=None, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Help on method_descriptor:
replace(self, old, new, count=-1, /)
Return a copy with all occurrences of substring old replaced by new.
You can query individual collection types and specific bound methods directly:
# 2. Inspecting built-in data types and methods
# Inspecting list method documentation
help(list.append)
# Inspecting dictionary fromkeys method
help(dict.fromkeys)Terminal Output:
Help on method_descriptor:
append(self, object, /)
Append object to the end of the list.
Help on built-in function fromkeys:
fromkeys(iterable, value=None, /) method of builtins.type instance
Create a new dictionary with keys from iterable and values set to value.
Calling help() with no arguments opens the interactive documentation utility in the console:
help() # Opens interactive help> console prompt
Within this interactive mode, type the name of any module, keyword, or topic. Type quit to return to Python.
You can look up Python reserved keywords and language concepts by passing their string names:
# 3. Querying language keywords and syntax topics
# Querying documentation for a specific language keyword
help('if')
# Querying Python language topics
help('FUNCTIONS')Terminal Output:
The "if" statement
******************
The "if" statement is used for conditional execution:
if_stmt ::= "if" assignment_expression ":" suite
("elif" assignment_expression ":" suite)*
["else" ":" suite]
Related help topics: TRUTHVALUE
| Category | Primary Reference Topics | Lookup Examples |
|---|---|---|
| Control Flow | CONDITIONAL, LOOPS, EXCEPTIONS |
help('if'), help('while') |
| Data Structures | SEQUENCES, MAPPINGS, LISTS, TUPLES |
help('LISTS'), help('STRINGS') |
| Operators | BITWISE, COMPARISON, BOOLEAN |
help('BITWISE'), help('BOOLEAN') |
| Architecture | NAMESPACES, SCOPING, IMPORTING |
help('MODULES'), help('PACKAGES') |
Behind the scenes, help() delegates to the standard library pydoc module. You can use pydoc.render_doc() in code to capture text in memory without opening a terminal pager:
# 4. Headless documentation extraction using pydoc
import pydoc
# Extract clean documentation string without invoking interactive terminal pager
doc_text = pydoc.render_doc(str.split, title="Method Documentation: %s")
print(doc_text[:280] + "...")Terminal Output:
Method Documentation: split(self, /, sep=None, maxsplit=-1) in module builtins
Return a list of the substrings in the string, using sep as the separator string.
sep
The delimiter according which to split the string.
None (the default value) means split according to any whitespace...
When you define custom classes and functions, help() parses docstring triple-quoted text into clean, structured sections:
# 5. Authoring structured docstrings for custom classes and functions
class DataFilter:
"""Utility class for sanitizing and transforming tabular records.
Attributes:
threshold (float): Numerical cutoff limit.
"""
def __init__(self, threshold: float = 0.0):
"""Initialize filter with optional threshold (default 0.0)."""
self.threshold = threshold
def apply(self, numbers: list) -> list:
"""Filter numbers strictly exceeding the threshold.
Args:
numbers (list): List of numeric values to filter.
Returns:
list: Values greater than threshold.
"""
return [n for n in numbers if n > self.threshold]
# Inspecting custom class documentation via help()
help(DataFilter)Terminal Output:
Help on class DataFilter in module __main__:
class DataFilter(builtins.object)
| DataFilter(threshold: float = 0.0)
|
| Utility class for sanitizing and transforming tabular records.
|
| Methods defined here:
|
| __init__(self, threshold: float = 0.0)
| Initialize filter with optional threshold (default 0.0).
|
| apply(self, numbers: list) -> list
| Filter numbers strictly exceeding the threshold.
Inspect and catalog public methods and their summary docstrings automatically:
# 6. Production Recipe: In-Memory Docstring Scraper & API Catalog
import inspect
def generate_api_catalog(module_or_class):
"""Scrapes and formats docstrings of all callable methods into an API catalog."""
catalog = {}
for name, member in inspect.getmembers(module_or_class):
if not name.startswith("_") and callable(member):
doc = inspect.getdoc(member) or "No documentation provided."
first_line = doc.split("\n")[0]
catalog[name] = first_line
return catalog
sample_catalog = generate_api_catalog(DataFilter)
for method, summary in sample_catalog.items():
print(f"{method:<10}: {summary}")Terminal Output:
apply : Filter numbers strictly exceeding the threshold.
Avoid executing the function when passing arguments to help():
# 7. Common traps: passing function call instead of reference
# Trap: help(print()) executes print() first and shows help(None)
print("--- Output of help(print) vs help(print()) ---")
# help(print()) <-- Pass 'print', NEVER 'print()' with parentheses!Terminal Output:
--- Output of help(print) vs help(print()) ---
Pass function reference 'print', not return value of function call 'print()'.
Practice documentation inspection, headless doc extraction with pydoc, and PEP 257 formatting in our interactive companion Jupyter Notebook:
Explore interactive code cells, practice headless docstring extraction with pydoc.render_doc(), inspect custom classes, and run self-validating assertions.
Run these unit checks directly in Python or your local environment to verify documentation extraction mechanics:
# 8. Self-verifying unit test suite for help() & pydoc
import pydoc
import inspect
# Test 1: Verify pydoc extraction returns non-empty documentation
doc_str = pydoc.render_doc(len)
assert "Return the number of items in a container" in doc_str
# Test 2: Verify custom docstring extraction
doc_class = inspect.getdoc(DataFilter)
assert "Utility class for sanitizing" in doc_class
# Test 3: Verify method docstring extraction
doc_method = inspect.getdoc(DataFilter.apply)
assert "Filter numbers strictly exceeding" in doc_method
print("All help() and pydoc unit assertions successfully verified!")Terminal Output:
All help() and pydoc unit assertions successfully verified!
Type quit and press Enter at the help> prompt to exit back to the standard Python prompt.
dir() returns a list of attribute names. help() returns human-readable documentation, signatures, and docstrings.
Yes. Run python -m pydoc math in your terminal or launch a local browser documentation server with python -m pydoc -b.
Because func() with parentheses executes the function first, passing its return value (often None) to help().
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.