Skip to content

Commit 63d8804

Browse files
authored
Use __qualname__ for nested class support and add DefaultPutDict test (#2859)
1 parent a3cd521 commit 63d8804

3 files changed

Lines changed: 28 additions & 2 deletions

File tree

src/datamodel_code_generator/__main__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -692,9 +692,9 @@ def _get_origin_name(origin: type) -> str:
692692
"""Get the fully qualified name of a generic origin.
693693
694694
For types from builtins, typing, or collections.abc, returns just the name.
695-
For other types (custom generics), returns module.name format.
695+
For other types (custom generics), returns module.qualname format.
696696
"""
697-
name = getattr(origin, "__name__", None)
697+
name = getattr(origin, "__qualname__", None) or getattr(origin, "__name__", None)
698698
if name:
699699
module = getattr(origin, "__module__", "")
700700
if module and module not in {"builtins", "typing", "collections.abc"}:

tests/data/python/input_model/pydantic_models.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,3 +105,15 @@ class ModelWithCustomGeneric(BaseModel):
105105
model_config = {"arbitrary_types_allowed": True}
106106
custom_dict: CustomGenericDict[str, int]
107107
optional_custom_dict: CustomGenericDict[str, str] | None
108+
109+
110+
# Import DefaultPutDict for testing real-world generic type import
111+
from datamodel_code_generator.parser import DefaultPutDict # noqa: E402
112+
113+
114+
class ModelWithDefaultPutDict(BaseModel):
115+
"""Model with DefaultPutDict to test generic type import from parser module."""
116+
117+
model_config = {"arbitrary_types_allowed": True}
118+
cache: DefaultPutDict[str, str]
119+
optional_cache: DefaultPutDict[str, int] | None

tests/test_input_model.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -741,6 +741,20 @@ def test_input_model_custom_generic_type_import(tmp_path: Path) -> None:
741741
)
742742

743743

744+
@SKIP_PYDANTIC_V1
745+
def test_input_model_default_put_dict_import(tmp_path: Path) -> None:
746+
"""Test that DefaultPutDict generic type is properly imported from parser module."""
747+
run_input_model_and_assert(
748+
input_model="tests.data.python.input_model.pydantic_models:ModelWithDefaultPutDict",
749+
output_path=tmp_path / "output.py",
750+
expected_output_contains=[
751+
"from datamodel_code_generator.parser import DefaultPutDict",
752+
"DefaultPutDict[str, str]",
753+
"DefaultPutDict[str, int] | None",
754+
],
755+
)
756+
757+
744758
# ============================================================================
745759
# --input-model-ref-strategy tests
746760
# ============================================================================

0 commit comments

Comments
 (0)