Skip to content

Commit b41bf46

Browse files
committed
fix: Don't crash when trying to evaluate AST literals (field descriptions)
Issue-16: #16
1 parent 6084186 commit b41bf46

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

src/griffe_pydantic/static.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,10 @@ def process_attribute(attr: Attribute, cls: Class, *, processed: set[str]) -> No
9797

9898
# Populate docstring from the field's `description` argument.
9999
if not attr.docstring and (docstring := kwargs.get("description", None)):
100-
attr.docstring = Docstring(ast.literal_eval(docstring), parent=attr) # type: ignore[arg-type]
100+
try:
101+
attr.docstring = Docstring(ast.literal_eval(docstring), parent=attr) # type: ignore[arg-type]
102+
except ValueError:
103+
logger.debug(f"Could not parse description of field '{attr.path}' as literal, skipping")
101104

102105

103106
def process_function(func: Function, cls: Class, *, processed: set[str]) -> None:

tests/test_extension.py

+26
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22

33
from __future__ import annotations
44

5+
import logging
56
from typing import TYPE_CHECKING
67

8+
import pytest
79
from griffe import Extensions, temporary_visited_package
810

911
from griffe_pydantic.extension import PydanticExtension
@@ -120,3 +122,27 @@ class Model(BaseModel):
120122
extensions=Extensions(PydanticExtension(schema=False)),
121123
) as package:
122124
python_handler.render(package["Model"], {}) # Assert no errors.
125+
126+
127+
def test_not_crashing_on_dynamic_field_description(caplog: pytest.LogCaptureFixture) -> None:
128+
"""Test the extension with dynamic field description."""
129+
code = """
130+
import pydantic
131+
132+
desc = "xyz"
133+
134+
class TestModel(pydantic.BaseModel):
135+
abc: str = pydantic.Field(description=desc)
136+
"""
137+
with (
138+
caplog.at_level(logging.DEBUG),
139+
temporary_visited_package(
140+
"package",
141+
modules={"__init__.py": code},
142+
extensions=Extensions(PydanticExtension(schema=False)),
143+
),
144+
):
145+
assert any(
146+
record.levelname == "DEBUG" and "field 'package.TestModel.abc' as literal" in record.message
147+
for record in caplog.records
148+
)

0 commit comments

Comments
 (0)