Auto-generate API documentation for Python projects with support for multiple docstring formats, type annotations, and customizable templates.
—
Advanced text processing utilities for converting docstrings, handling multiple documentation formats, generating HTML output, and processing mathematical expressions with cross-linking support.
Convert docstrings between different formats with support for NumPy, Google, and reStructuredText styles.
def to_html(text, docformat=None, module=None, link=None, latex_math=False) -> str:
"""
Convert docstring text to HTML with formatting and cross-linking.
Parameters:
- text: Input docstring text
- docformat: Documentation format ('numpy', 'google', None for auto-detect)
- module: Module object for identifier resolution and cross-linking
- link: Function to generate cross-reference links (takes Doc object, returns str)
- latex_math: If True, enable LaTeX math processing with MathJax
Returns:
str: Formatted HTML with syntax highlighting and cross-links
"""
def to_markdown(text, docformat=None, module=None, link=None) -> str:
"""
Convert docstring text to Markdown format.
Parameters:
- text: Input docstring text
- docformat: Documentation format ('numpy', 'google', None for auto-detect)
- module: Module object for identifier resolution
- link: Function to generate cross-reference links
Returns:
str: Formatted Markdown text
"""Minify and optimize HTML and CSS content for production deployment.
def minify_html(html: str) -> str:
"""
Minify HTML by replacing consecutive whitespace with single characters.
Parameters:
- html: Input HTML string
Returns:
str: Minified HTML (preserves <pre> tag contents)
"""
def minify_css(css: str) -> str:
"""
Minify CSS by removing whitespace, comments, and trailing semicolons.
Parameters:
- css: Input CSS string
Returns:
str: Minified CSS string
"""Extract and format text content for summaries, previews, and content organization.
def glimpse(text: str, max_length=153, paragraph=True) -> str:
"""
Extract short excerpt from text for previews and summaries.
Parameters:
- text: Input text
- max_length: Maximum excerpt length in characters
- paragraph: If True, break at paragraph boundaries when possible
Returns:
str: Text excerpt, potentially truncated with ellipsis
"""
def extract_toc(text: str) -> str:
"""
Extract table of contents from Markdown text based on headers.
Parameters:
- text: Markdown text with headers
Returns:
str: Table of contents as nested list
"""Generate links to source code in version control systems.
def format_git_link(template: str, dobj: 'Doc') -> Optional[str]:
"""
Format git repository links using template and documentation object.
Parameters:
- template: URL template with placeholders like {path}, {start_line}, {end_line}
- dobj: Documentation object with source information
Returns:
Optional[str]: Formatted URL or None if template cannot be resolved
Template placeholders:
- {path}: File path relative to repository root
- {start_line}: Starting line number of object definition
- {end_line}: Ending line number of object definition
"""Specialized processors for different docstring formats and markup languages.
class _ToMarkdown:
@staticmethod
def numpy(text: str) -> str:
"""
Convert NumPy-style docstrings to Markdown.
Parameters:
- text: NumPy docstring text
Returns:
str: Markdown formatted text
"""
@staticmethod
def google(text: str) -> str:
"""
Convert Google-style docstrings to Markdown.
Parameters:
- text: Google docstring text
Returns:
str: Markdown formatted text
"""
@staticmethod
def admonitions(text: str, module: 'Module', limit_types=None) -> str:
"""
Process reStructuredText directives and admonitions.
Parameters:
- text: Text with reST directives
- module: Module for file path resolution
- limit_types: Optional tuple of directive types to process
Returns:
str: Processed text with directives converted to Markdown
"""
@staticmethod
def doctests(text: str) -> str:
"""
Fence Python doctest blocks for proper syntax highlighting.
Parameters:
- text: Text containing doctest examples
Returns:
str: Text with doctests wrapped in code fences
"""
@staticmethod
def raw_urls(text: str) -> str:
"""
Wrap raw URLs in angle brackets for Markdown processing.
Parameters:
- text: Text containing URLs
Returns:
str: Text with URLs properly formatted
"""
@staticmethod
def indent(indent: str, text: str, clean_first=False) -> str:
"""
Add indentation to text lines.
Parameters:
- indent: Indentation string to add
- text: Text to indent
- clean_first: If True, remove existing indentation first
Returns:
str: Indented text
"""Process LaTeX mathematical expressions for web display.
class _MathPattern(InlineProcessor):
"""
Markdown processor for LaTeX math expressions.
Processes:
- Inline math: $expression$
- Display math: $$expression$$
Converts to MathJax-compatible HTML elements.
"""Custom warnings for documentation processing issues.
class ReferenceWarning(UserWarning):
"""
Warning raised when Markdown object references don't match documented objects.
Occurs when cross-references in docstrings cannot be resolved to actual
documented identifiers.
"""Pre-configured Markdown processor with extensions for documentation.
_md: markdown.Markdown # Configured with extensions for code, tables, etc.from pdoc.html_helpers import to_html, to_markdown
import pdoc
# Convert docstring to HTML
module = pdoc.Module('mymodule')
docstring = """
This is a function that does something important.
Parameters:
x (int): The input value
y (str): The string parameter
Returns:
bool: True if successful
"""
html_output = to_html(docstring, docformat='numpy', module=module)
markdown_output = to_markdown(docstring, docformat='numpy')from pdoc.html_helpers import to_html
import pdoc
def create_link_function(base_url):
"""Create a link function for cross-references."""
def link_func(doc_obj):
return f"{base_url}/{doc_obj.url()}"
return link_func
module = pdoc.Module('mypackage')
pdoc.link_inheritance()
# Convert with cross-linking
link_fn = create_link_function('https://docs.myproject.com')
html_doc = to_html(
module.docstring,
module=module,
link=link_fn,
latex_math=True
)from pdoc.html_helpers import minify_html, minify_css, glimpse
# Generate documentation
html_doc = pdoc.html('mymodule')
# Optimize for production
minified_html = minify_html(html_doc)
# Extract preview text
preview = glimpse(module.docstring, max_length=200)
# Process CSS
css_content = """
.doc {
margin: 10px;
padding: 20px;
/* This is a comment */
background-color: #ffffff;
}
"""
minified_css = minify_css(css_content)from pdoc.html_helpers import format_git_link
import pdoc
# Configure git link template
git_template = "https://github.com/user/repo/blob/main/{path}#L{start_line}-L{end_line}"
module = pdoc.Module('mypackage')
# Generate git links for all functions
for name, obj in module.doc.items():
if isinstance(obj, pdoc.Function):
git_url = format_git_link(git_template, obj)
if git_url:
print(f"{obj.name}: {git_url}")from pdoc.html_helpers import _ToMarkdown
# Process different docstring formats
numpy_docstring = """
Brief description.
Parameters
----------
x : int
Parameter description
y : str, optional
Another parameter
Returns
-------
bool
Return description
"""
google_docstring = """
Brief description.
Args:
x (int): Parameter description
y (str, optional): Another parameter
Returns:
bool: Return description
"""
# Convert to Markdown
numpy_md = _ToMarkdown.numpy(numpy_docstring)
google_md = _ToMarkdown.google(google_docstring)
# Process doctests
doctest_text = """
Example usage:
>>> x = 5
>>> result = my_function(x)
>>> print(result)
True
"""
processed_doctests = _ToMarkdown.doctests(doctest_text)from pdoc.html_helpers import extract_toc
markdown_text = """
# Main Title
Some introduction text.
## Section 1
Content for section 1.
### Subsection 1.1
More detailed content.
## Section 2
Content for section 2.
"""
toc = extract_toc(markdown_text)
print(toc)
# Output:
# - [Main Title](#main-title)
# - [Section 1](#section-1)
# - [Subsection 1.1](#subsection-1-1)
# - [Section 2](#section-2)from pdoc.html_helpers import to_html, ReferenceWarning
import warnings
import pdoc
# Capture reference warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
docstring_with_refs = """
This function uses `nonexistent.Class` and `undefined_function()`.
"""
module = pdoc.Module('mymodule')
html_result = to_html(docstring_with_refs, module=module)
# Check for reference warnings
ref_warnings = [warning for warning in w if issubclass(warning.category, ReferenceWarning)]
for warning in ref_warnings:
print(f"Reference warning: {warning.message}")Install with Tessl CLI
npx tessl i tessl/pypi-pdoc3