CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-sphinx-automodapi

Sphinx extension for auto-generating API documentation for entire modules

Pending
Overview
Eval results
Files

utilities.mddocs/

Utilities

Functions for discovering module objects, processing text, and handling integration with Sphinx's autosummary system. These utilities power the directive functionality and can be used programmatically for custom documentation workflows.

Capabilities

Module Object Discovery

Functions for finding and filtering public objects in Python modules, respecting __all__ declarations and package boundaries.

def find_mod_objs(modname: str, onlylocals: bool | list = False, sort: bool = False) -> tuple[list[str], list[str], list[object]]:
    """
    Find all public objects in a module.
    
    Parameters:
    - modname: The name of the module to search
    - onlylocals: If True, only include objects defined in this module.
                 If False, include imported objects. If a list, only include
                 objects from packages in the list. Ignored if module defines __all__
    - sort: If True and module doesn't have __all__, sort objects alphabetically
    
    Returns:
    - tuple: Three lists:
        - localnames: List of object names as they appear in the module
        - fqnames: List of fully qualified names (e.g., 'package.module.Class')
        - objs: List of the actual objects themselves
    
    Notes:
    - Respects __all__ if defined in the module
    - Excludes private objects (names starting with '_')
    - Does not include submodules or subpackages
    """

Usage Example

from sphinx_automodapi.utils import find_mod_objs

# Find all public objects in a module
localnames, fqnames, objects = find_mod_objs('mypackage.utils')
for name, fqname, obj in zip(localnames, fqnames, objects):
    print(f"{name} -> {fqname}: {type(obj).__name__}")

# Find only locally defined objects, sorted
localnames, fqnames, objects = find_mod_objs('mypackage.core', onlylocals=True, sort=True)

Text Processing

Utilities for cleaning up generated documentation text to ensure proper formatting and whitespace handling.

def cleanup_whitespace(text: str) -> str:
    """
    Clean up whitespace in generated text.
    
    - Ensures no more than two consecutive newlines
    - Removes trailing whitespace from each line
    - Adds a single trailing newline
    
    Parameters:
    - text: Input text to clean up
    
    Returns:
    - str: Cleaned text with normalized whitespace
    """

Usage Example

from sphinx_automodapi.utils import cleanup_whitespace

# Clean up generated documentation text
raw_text = "Some text   \n\n\n\nMore text \n"
clean_text = cleanup_whitespace(raw_text)
# Result: "Some text\n\nMore text\n"

Autosummary Integration

Functions for integrating with Sphinx's autosummary system, handling the discovery and processing of autosummary directives within automodsumm contexts.

def find_autosummary_in_lines_for_automodsumm(lines: list[str], module: str = None, 
                                             filename: str = None) -> list:
    """
    Find autosummary directives in lines for automodsumm processing.
    
    Modified version of sphinx.ext.autosummary's find_autosummary_in_docstring
    that works with automodsumm directive processing.
    
    Parameters:
    - lines: List of lines to search for autosummary directives
    - module: Module name context for resolving references
    - filename: Filename context for error reporting
    
    Returns:
    - list: List of discovered autosummary items
    """

Usage Example

from sphinx_automodapi.utils import find_autosummary_in_lines_for_automodsumm

# Process lines containing autosummary directives
lines = [
    ".. autosummary::",
    "   :toctree: generated/",
    "",
    "   function1",
    "   Class1"
]

autosummary_items = find_autosummary_in_lines_for_automodsumm(
    lines, module='mypackage.core'
)

Document Generation Functions

Higher-level functions for generating documentation content from automodsumm directives.

def automodsumm_to_autosummary_lines(fn: str, app: Sphinx) -> list[str]:
    """
    Convert automodsumm file to autosummary lines.
    
    Parameters:
    - fn: Filename containing automodsumm directives
    - app: Sphinx application instance
    
    Returns:
    - list: Lines converted to autosummary format
    """

def generate_automodsumm_docs(lines: list[str], srcfn: str, app: Sphinx = None, 
                             suffix: str = '.rst', base_path: str = None,
                             builder=None, template_dir: str = None,
                             inherited_members: bool = False,
                             included_members: tuple = ('__init__', '__call__'),
                             properties_are_attributes: bool = True, **kwargs) -> None:
    """
    Generate documentation from automodsumm lines.
    
    Parameters:
    - lines: Lines containing automodsumm directives
    - srcfn: Source filename
    - app: Sphinx application instance
    - suffix: File suffix for generated files
    - base_path: Base path for generated files
    - builder: Sphinx builder instance
    - template_dir: Directory containing custom templates
    - inherited_members: Include inherited class members
    - included_members: Special method names to include
    - properties_are_attributes: Treat properties as attributes
    - **kwargs: Additional options passed to generation
    """

def process_automodsumm_generation(app: Sphinx) -> None:
    """
    Process automodsumm generation for all documents.
    
    Connected to Sphinx's 'builder-inited' event to generate documentation
    for all automodsumm directives found in the project.
    
    Parameters:
    - app: Sphinx application instance
    """

Internal Constants

# Text processing constants
SPACE_NEWLINE: str = ' \n'
SINGLE_NEWLINE: str = '\n'
DOUBLE_NEWLINE: str = '\n\n'
TRIPLE_NEWLINE: str = '\n\n\n'

Implementation Notes

Module Object Discovery Logic

The find_mod_objs function implements sophisticated logic for determining which objects to include:

  1. all handling: If a module defines __all__, only objects listed there are included
  2. Local filtering: When onlylocals=True, only objects defined in the target module are included
  3. Package filtering: When onlylocals is a list, only objects from specified packages are included
  4. Private filtering: Objects with names starting with underscore are excluded
  5. Sorting: Objects can be sorted alphabetically when __all__ is not defined

Text Normalization

The cleanup_whitespace function ensures consistent formatting by:

  1. Removing trailing whitespace from each line
  2. Limiting consecutive newlines to maximum of two
  3. Ensuring the text ends with exactly one newline
  4. Preserving overall text structure and content

This normalization is essential for generating clean, consistent documentation output that integrates well with Sphinx's processing pipeline.

Install with Tessl CLI

npx tessl i tessl/pypi-sphinx-automodapi

docs

autodoc-enhancements.md

configuration.md

directives.md

index.md

smart-resolution.md

utilities.md

tile.json