Extract Python API signatures and detect breaking changes for documentation generation.
—
High-level functions for loading Python packages and modules from different sources. Loaders orchestrate the analysis process using both static analysis (AST parsing) and dynamic analysis (runtime inspection) to extract comprehensive API information.
Load a Python package or module from the current environment.
def load(
objspec: str | Path | None = None,
/,
*,
submodules: bool = True,
try_relative_path: bool = True,
extensions: Extensions | None = None,
search_paths: Sequence[str | Path] | None = None,
docstring_parser: DocstringStyle | Parser | None = None,
docstring_options: dict[str, Any] | None = None,
lines_collection: LinesCollection | None = None,
modules_collection: ModulesCollection | None = None,
allow_inspection: bool = True,
force_inspection: bool = False,
store_source: bool = True,
find_stubs_package: bool = False,
resolve_aliases: bool = False,
resolve_external: bool | None = None,
resolve_implicit: bool = False,
) -> Object | Alias:
"""
Load and return a Griffe object from a module specification.
Main high-level function for loading API data from Python packages.
Supports both static analysis via AST parsing and dynamic analysis
via runtime inspection.
Args:
objspec: Module specification (e.g., 'requests', 'requests.api.get') or Path object
submodules: Whether to load submodules automatically
try_relative_path: Whether to try loading as relative path
extensions: Extensions to use during loading
search_paths: Additional paths to search for modules (Sequence instead of list)
docstring_parser: Parser for docstrings (DocstringStyle enum or Parser)
docstring_options: Options passed to docstring parser
lines_collection: Collection to store source lines
modules_collection: Collection to store loaded modules
allow_inspection: Whether to allow runtime inspection fallback
force_inspection: Whether to force runtime inspection even when AST available
store_source: Whether to store source code in objects
find_stubs_package: Whether to search for stub packages
resolve_aliases: Whether to resolve aliases immediately
resolve_external: Whether to resolve external aliases
resolve_implicit: Whether to resolve implicit aliases
Returns:
Object | Alias: The loaded module, class, function, attribute, or alias
Raises:
LoadingError: If the module cannot be loaded
NameResolutionError: If the object specification cannot be resolved
"""Load a package from a specific Git reference (commit, branch, or tag).
def load_git(
objspec: str,
ref: str = "HEAD",
*,
repo: str | Path = ".",
**load_kwargs: Any,
) -> Object:
"""
Load and return a module from a specific Git reference.
Allows loading API data from a specific commit, branch, or tag in a Git
repository. Useful for comparing different versions or analyzing historical APIs.
Args:
objspec: Module specification to load
ref: Git reference (commit hash, branch name, or tag)
repo: Path to the Git repository (default: current directory)
**load_kwargs: Additional arguments passed to load()
Returns:
Object: The loaded object from the specified Git reference
Raises:
GitError: If Git operations fail
LoadingError: If the module cannot be loaded from the Git reference
Examples:
Load from a specific tag:
>>> old_api = griffe.load_git("mypackage", ref="v1.0.0")
Load from a branch:
>>> feature_api = griffe.load_git("mypackage", ref="feature-branch")
Load from a commit:
>>> commit_api = griffe.load_git("mypackage", ref="abc123def")
"""Load a package from PyPI (Python Package Index) at a specific version.
def load_pypi(
package: str,
distribution: str,
version_spec: str,
*,
submodules: bool = True,
extensions: Extensions | None = None,
search_paths: Sequence[str | Path] | None = None,
docstring_parser: DocstringStyle | Parser | None = None,
docstring_options: dict[str, Any] | None = None,
lines_collection: LinesCollection | None = None,
modules_collection: ModulesCollection | None = None,
allow_inspection: bool = True,
force_inspection: bool = False,
find_stubs_package: bool = False,
) -> Object | Alias:
"""
Load and return a module from a specific package version downloaded using pip.
Enables loading API data from PyPI packages at specific versions.
Requires the 'pypi' extra: pip install griffe[pypi]
Args:
package: The package import name
distribution: The distribution name
version_spec: The version specifier to use when installing with pip
submodules: Whether to recurse on the submodules
extensions: The extensions to use
search_paths: The paths to search into
docstring_parser: The docstring parser to use
docstring_options: The docstring parser options
lines_collection: A collection of source code lines
modules_collection: A collection of modules
allow_inspection: Whether to allow inspecting modules when visiting them is not possible
force_inspection: Whether to force using dynamic analysis when loading data
find_stubs_package: Whether to search for stubs packages
Returns:
Object | Alias: The loaded object from the PyPI package
Raises:
LoadingError: If the package cannot be downloaded or loaded
Examples:
Load latest version:
>>> package = griffe.load_pypi("requests")
Load specific version:
>>> old_django = griffe.load_pypi("django", "3.2.0")
Load with version constraints:
>>> fastapi = griffe.load_pypi("fastapi", ">=0.68.0,<1.0.0")
"""Advanced loader class for fine-grained control over the loading process.
class GriffeLoader:
"""
Main loader class that handles the loading process.
Provides configurable options for extensions, search paths,
docstring parsing, and more advanced loading scenarios.
"""
def __init__(
self,
*,
search_paths: Sequence[str | Path] | None = None,
docstring_parser: Parser | None = None,
docstring_options: dict[str, Any] | None = None,
lines_collection: LinesCollection | None = None,
modules_collection: ModulesCollection | None = None,
allow_inspection: bool = True,
store_source: bool = True,
extensions: Extensions | None = None,
) -> None:
"""
Initialize the loader.
Args:
search_paths: Directories to search for modules
docstring_parser: Parser for processing docstrings
docstring_options: Configuration for docstring parsing
lines_collection: Collection for source code lines
modules_collection: Collection for loaded modules
allow_inspection: Enable runtime inspection fallback
store_source: Store source code in loaded objects
extensions: Extensions to apply during loading
"""
def load(
self,
objspec: str,
*,
try_relative_path: bool = True,
resolve_aliases: bool = False,
resolve_external: bool | None = None,
resolve_implicit: bool = False,
) -> Object:
"""
Load an object using this loader's configuration.
Args:
objspec: Object specification to load
try_relative_path: Try loading as relative path
resolve_aliases: Resolve aliases immediately
resolve_external: Resolve external aliases
resolve_implicit: Resolve implicit aliases
Returns:
Object: The loaded object
"""
def load_module(
self,
module_name: str,
filepath: str | Path | None = None,
parent: Module | None = None,
) -> Module:
"""
Load a specific module.
Args:
module_name: Name of the module to load
filepath: Path to the module file (optional)
parent: Parent module (for submodules)
Returns:
Module: The loaded module
"""import griffe
# Load a package
requests_api = griffe.load("requests")
print(f"Package: {requests_api.name}")
print(f"Modules: {list(requests_api.modules.keys())}")
# Load a specific function
get_function = griffe.load("requests.api.get")
print(f"Function: {get_function.name}")
print(f"Parameters: {[p.name for p in get_function.parameters]}")import griffe
# Compare current version with previous Git tag
old_version = griffe.load_git("mypackage", ref="v1.0.0")
current_version = griffe.load("mypackage")
# Compare PyPI versions
old_pypi = griffe.load_pypi("django", "3.2.0")
new_pypi = griffe.load_pypi("django", "4.0.0")
breakages = griffe.find_breaking_changes(old_pypi, new_pypi)
for breakage in breakages:
print(f"Breaking change: {breakage}")import griffe
from griffe import Extensions, Parser
# Configure custom loader
extensions = griffe.load_extensions(["dataclasses"])
loader = griffe.GriffeLoader(
docstring_parser=Parser.GOOGLE,
docstring_options={"style": "google"},
extensions=extensions,
allow_inspection=False, # Static analysis only
store_source=True,
)
# Load with custom configuration
package = loader.load("mypackage")
# Configure search paths
loader_with_paths = griffe.GriffeLoader(
search_paths=["src", "lib", "/opt/custom-packages"]
)
custom_package = loader_with_paths.load("custom_module")import griffe
from griffe import LoadingError, NameResolutionError, GitError
try:
package = griffe.load("nonexistent_package")
except LoadingError as e:
print(f"Failed to load package: {e}")
try:
git_package = griffe.load_git("mypackage", ref="invalid-ref")
except GitError as e:
print(f"Git error: {e}")
try:
specific_func = griffe.load("mypackage.nonexistent.function")
except NameResolutionError as e:
print(f"Cannot resolve name: {e}")from pathlib import Path
from typing import Any, Sequence
from enum import Enum
class Parser(Enum):
"""Docstring parser types."""
AUTO = "auto"
GOOGLE = "google"
NUMPY = "numpy"
SPHINX = "sphinx"
# Collection types
class LinesCollection:
"""Collection for managing source code lines."""
class ModulesCollection:
"""Collection for managing loaded modules."""
class Extensions:
"""Container for Griffe extensions."""Install with Tessl CLI
npx tessl i tessl/pypi-griffe