|
| 1 | +"""Utilities for parsing function docstrings to extract descriptions and parameter info. |
| 2 | +
|
| 3 | +Supports Google, NumPy, and Sphinx docstring formats with automatic detection. |
| 4 | +Adapted from pydantic-ai's _griffe.py implementation. |
| 5 | +""" |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +import logging |
| 10 | +import re |
| 11 | +from collections.abc import Callable |
| 12 | +from contextlib import contextmanager |
| 13 | +from typing import Any, Iterator, Literal |
| 14 | + |
| 15 | +from griffe import Docstring, DocstringSectionKind |
| 16 | + |
| 17 | +try: |
| 18 | + from griffe import GoogleOptions |
| 19 | + |
| 20 | + _GOOGLE_PARSER_OPTIONS = GoogleOptions(returns_named_value=False, returns_multiple_items=False) |
| 21 | +except ImportError: |
| 22 | + _GOOGLE_PARSER_OPTIONS = None |
| 23 | + |
| 24 | +DocstringStyle = Literal["google", "numpy", "sphinx"] |
| 25 | + |
| 26 | + |
| 27 | +def parse_docstring( |
| 28 | + func: Callable[..., Any], |
| 29 | +) -> tuple[str | None, dict[str, str]]: |
| 30 | + """Extract the function summary and parameter descriptions from a docstring. |
| 31 | +
|
| 32 | + Automatically infers the docstring format (Google, NumPy, or Sphinx). |
| 33 | +
|
| 34 | + Returns: |
| 35 | + A tuple of (summary, param_descriptions) where: |
| 36 | + - summary: The main description text (first section), or None if no docstring |
| 37 | + - param_descriptions: Dict mapping parameter names to their descriptions |
| 38 | + """ |
| 39 | + doc = func.__doc__ |
| 40 | + if doc is None: |
| 41 | + return None, {} |
| 42 | + |
| 43 | + docstring_style = _infer_docstring_style(doc) |
| 44 | + parser_options = _GOOGLE_PARSER_OPTIONS if docstring_style == "google" else None |
| 45 | + docstring = Docstring( |
| 46 | + doc, |
| 47 | + lineno=1, |
| 48 | + parser=docstring_style, |
| 49 | + parser_options=parser_options, |
| 50 | + ) |
| 51 | + with _disable_griffe_logging(): |
| 52 | + sections = docstring.parse() |
| 53 | + |
| 54 | + params: dict[str, str] = {} |
| 55 | + if parameters := next( |
| 56 | + (s for s in sections if s.kind == DocstringSectionKind.parameters), None |
| 57 | + ): |
| 58 | + params = {p.name: p.description for p in parameters.value if p.description} |
| 59 | + |
| 60 | + summary: str | None = None |
| 61 | + if main := next( |
| 62 | + (s for s in sections if s.kind == DocstringSectionKind.text), None |
| 63 | + ): |
| 64 | + summary = main.value.strip() if main.value else None |
| 65 | + |
| 66 | + return summary, params |
| 67 | + |
| 68 | + |
| 69 | +def _infer_docstring_style(doc: str) -> DocstringStyle: |
| 70 | + """Infer the docstring style from its content.""" |
| 71 | + for pattern, replacements, style in _DOCSTRING_STYLE_PATTERNS: |
| 72 | + matches = ( |
| 73 | + re.search(pattern.format(replacement), doc, re.IGNORECASE | re.MULTILINE) |
| 74 | + for replacement in replacements |
| 75 | + ) |
| 76 | + if any(matches): |
| 77 | + return style |
| 78 | + return "google" |
| 79 | + |
| 80 | + |
| 81 | +# Pattern matching for docstring style detection. |
| 82 | +# See https://github.com/mkdocstrings/griffe/issues/329#issuecomment-2425017804 |
| 83 | +_DOCSTRING_STYLE_PATTERNS: list[tuple[str, list[str], DocstringStyle]] = [ |
| 84 | + ( |
| 85 | + r"\n[ \t]*:{0}([ \t]+\w+)*:([ \t]+.+)?\n", |
| 86 | + [ |
| 87 | + "param", |
| 88 | + "parameter", |
| 89 | + "arg", |
| 90 | + "argument", |
| 91 | + "type", |
| 92 | + "returns", |
| 93 | + "return", |
| 94 | + "rtype", |
| 95 | + "raises", |
| 96 | + "raise", |
| 97 | + ], |
| 98 | + "sphinx", |
| 99 | + ), |
| 100 | + ( |
| 101 | + r"\n[ \t]*{0}:([ \t]+.+)?\n[ \t]+.+", |
| 102 | + [ |
| 103 | + "args", |
| 104 | + "arguments", |
| 105 | + "params", |
| 106 | + "parameters", |
| 107 | + "raises", |
| 108 | + "returns", |
| 109 | + "yields", |
| 110 | + "examples", |
| 111 | + "attributes", |
| 112 | + ], |
| 113 | + "google", |
| 114 | + ), |
| 115 | + ( |
| 116 | + r"\n[ \t]*{0}\n[ \t]*---+\n", |
| 117 | + [ |
| 118 | + "parameters", |
| 119 | + "returns", |
| 120 | + "yields", |
| 121 | + "raises", |
| 122 | + "attributes", |
| 123 | + ], |
| 124 | + "numpy", |
| 125 | + ), |
| 126 | +] |
| 127 | + |
| 128 | + |
| 129 | +@contextmanager |
| 130 | +def _disable_griffe_logging() -> Iterator[None]: |
| 131 | + """Temporarily suppress griffe logging to avoid noisy warnings.""" |
| 132 | + old_level = logging.root.getEffectiveLevel() |
| 133 | + logging.root.setLevel(logging.ERROR) |
| 134 | + try: |
| 135 | + yield |
| 136 | + finally: |
| 137 | + logging.root.setLevel(old_level) |
0 commit comments