| 1 |
# Custom extensions for Griffe. |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import ast |
| 6 |
from typing import Any |
| 7 |
|
| 8 |
import griffe |
| 9 |
|
| 10 |
_logger = griffe.get_logger("griffe_extensions") |
| 11 |
|
| 12 |
|
| 13 |
class CustomFields(griffe.Extension): |
| 14 |
"""Support our custom dataclass fields.""" |
| 15 |
|
| 16 |
def on_attribute_instance( |
| 17 |
self, |
| 18 |
*, |
| 19 |
attr: griffe.Attribute, |
| 20 |
agent: griffe.Visitor | griffe.Inspector, |
| 21 |
**kwargs: Any, # noqa: ARG002 |
| 22 |
) -> None: |
| 23 |
"""Fetch descriptions from `Field` annotations.""" |
| 24 |
if attr.docstring: |
| 25 |
return |
| 26 |
annotation = attr.annotation |
| 27 |
if not isinstance(annotation, griffe.ExprSubscript) or not isinstance(annotation.slice, griffe.ExprTuple): |
| 28 |
return |
| 29 |
try: |
| 30 |
field = annotation.slice.elements[1] |
| 31 |
except IndexError: |
| 32 |
return |
| 33 |
if not isinstance(field, griffe.ExprCall): |
| 34 |
return |
| 35 |
|
| 36 |
if field.canonical_path == "mkdocstrings_handlers.python._internal.config._Field": |
| 37 |
description = next( |
| 38 |
attr.value |
| 39 |
for attr in field.arguments |
| 40 |
if isinstance(attr, griffe.ExprKeyword) and attr.name == "description" |
| 41 |
) |
| 42 |
if not isinstance(description, str): |
| 43 |
_logger.warning(f"Field description of {attr.path} is not a static string") |
| 44 |
description = str(description) |
| 45 |
|
| 46 |
attr.docstring = griffe.Docstring( |
| 47 |
ast.literal_eval(description), |
| 48 |
parent=attr, |
| 49 |
parser=agent.docstring_parser, |
| 50 |
parser_options=agent.docstring_options, |
| 51 |
) |