# This module implements a handler for the Python language. from __future__ import annotations import glob import inspect import os import posixpath import sys from contextlib import suppress from dataclasses import asdict from pathlib import Path from typing import TYPE_CHECKING, Any, BinaryIO, Callable, ClassVar from griffe import ( AliasResolutionError, GriffeLoader, LinesCollection, ModulesCollection, Parser, load_extensions, parse_auto, parse_google, parse_numpy, parse_sphinx, patch_loggers, ) from mkdocs.exceptions import PluginError from mkdocs_autorefs import BacklinkCrumb from mkdocstrings import BaseHandler, CollectionError, CollectorItem, HandlerOptions, Inventory, get_logger from mkdocstrings_handlers.python._internal import rendering from mkdocstrings_handlers.python._internal.config import PythonConfig, PythonOptions if TYPE_CHECKING: from collections.abc import Iterable, Iterator, Mapping, MutableMapping, Sequence from mkdocs.config.defaults import MkDocsConfig from mkdocs_autorefs import Backlink # YORE: EOL 3.10: Replace block with line 2. if sys.version_info >= (3, 11): from contextlib import chdir else: from contextlib import contextmanager @contextmanager def chdir(path: str) -> Iterator[None]: old_wd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(old_wd) _logger = get_logger(__name__) patch_loggers(get_logger) _PARSER_FUNCTIONS: dict[Parser, Callable] = { Parser.auto: parse_auto, Parser.google: parse_google, Parser.numpy: parse_numpy, Parser.sphinx: parse_sphinx, } def _filter_parser_options(parser: Parser | None, options: dict[str, Any] | None) -> dict[str, Any] | None: """Filter options unsupported by the selected Griffe parser.""" if parser is None or options is None: return options accepted_options = set(inspect.signature(_PARSER_FUNCTIONS[parser]).parameters) - {"docstring"} filtered_options = {} for name, value in options.items(): if name in accepted_options: if parser is Parser.auto and name == "per_style_options": filtered_options[name] = { style: _filter_parser_options(Parser(style), style_options) for style, style_options in value.items() } else: filtered_options[name] = value else: _logger.warning(f"Ignoring unsupported {parser.value} docstring parser option: {name}") return filtered_options class PythonHandler(BaseHandler): """The Python handler class.""" name: ClassVar[str] = "python" """The handler's name.""" domain: ClassVar[str] = "py" """The cross-documentation domain/language for this handler.""" enable_inventory: ClassVar[bool] = True """Whether this handler is interested in enabling the creation of the `objects.inv` Sphinx inventory file.""" fallback_theme: ClassVar[str] = "material" """The fallback theme.""" def __init__(self, config: PythonConfig, base_dir: Path, **kwargs: Any) -> None: """Initialize the handler. Parameters: config: The handler configuration. base_dir: The base directory of the project. **kwargs: Arguments passed to the parent constructor. """ super().__init__(**kwargs) self.config = config """The handler configuration.""" self.base_dir = base_dir """The base directory of the project.""" self.global_options = config.options """The global configuration options (in `mkdocs.yml`).""" # Warn if user overrides base templates. if self.custom_templates: for theme_dir in base_dir.joinpath(self.custom_templates, "python").iterdir(): if theme_dir.joinpath("_base").is_dir(): _logger.warning( f"Overriding base template '{theme_dir.name}/_base/