Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion src/datamodel_code_generator/parser/jsonschema.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import enum as _enum
import json
import re
from collections import defaultdict
from collections.abc import Iterable
from contextlib import contextmanager, suppress
Expand Down Expand Up @@ -1334,6 +1335,13 @@ def _is_compatible_python_type(self, schema_type: str | None, python_type: str)
compatible = self.COMPATIBLE_PYTHON_TYPES.get(schema_type, frozenset())
return base_type in compatible

def _extract_all_type_names(self, type_str: str) -> list[str]: # noqa: PLR6301
"""Extract all type names from a type annotation string."""
# Match type names: word characters starting with uppercase, not preceded by a dot
# This handles cases like Callable[[Iterable[str]], str]
pattern = r"(?<![.\w])([A-Z]\w*)"
return re.findall(pattern, type_str)

def _get_python_type_override(self, obj: JsonSchemaObject) -> DataType | None:
"""Get DataType from x-python-type if it's incompatible with schema type."""
x_python_type = obj.extras.get("x-python-type")
Expand All @@ -1357,7 +1365,18 @@ def _get_python_type_override(self, obj: JsonSchemaObject) -> DataType | None:
# If not in predefined imports, create import from the full path
import_ = Import.from_full_path(prefix)

return self.data_type(type=type_str, import_=import_)
# Collect imports for all nested types (e.g., Iterable inside Callable[[Iterable[str]], str])
nested_imports: list[DataType] = []
for type_name in self._extract_all_type_names(type_str):
if type_name != base_type:
nested_import = self.PYTHON_TYPE_IMPORTS.get(type_name)
if nested_import:
nested_imports.append(self.data_type(import_=nested_import))

result = self.data_type(type=type_str, import_=import_)
if nested_imports:
result.data_types.extend(nested_imports)
return result

def _apply_title_as_name(self, name: str, obj: JsonSchemaObject) -> str:
"""Apply title as name if use_title_as_name is enabled."""
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# generated by datamodel-codegen:
# filename: x_python_type_nested_imports.json
# timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from collections.abc import Callable, Iterable
from typing import TypedDict

from typing_extensions import NotRequired


class Model(TypedDict):
callback: NotRequired[Callable[[Iterable[str]], str]]
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# generated by datamodel-codegen:
# filename: x_python_type_nested_unknown_type.json
# timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from collections.abc import Callable
from typing import TypedDict

from typing_extensions import NotRequired


class Model(TypedDict):
callback: NotRequired[Callable[[MyCustomType[str]], str]]
9 changes: 9 additions & 0 deletions tests/data/jsonschema/x_python_type_nested_imports.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"type": "object",
"properties": {
"callback": {
"type": "string",
"x-python-type": "Callable[[Iterable[str]], str]"
}
}
}
9 changes: 9 additions & 0 deletions tests/data/jsonschema/x_python_type_nested_unknown_type.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"type": "object",
"properties": {
"callback": {
"type": "string",
"x-python-type": "Callable[[MyCustomType[str]], str]"
}
}
}
22 changes: 22 additions & 0 deletions tests/main/jsonschema/test_main_jsonschema.py
Original file line number Diff line number Diff line change
Expand Up @@ -7031,3 +7031,25 @@ def test_x_python_type_custom_fqpath(output_file: Path) -> None:
assert_func=assert_file_content,
extra_args=["--output-model-type", "typing.TypedDict"],
)


def test_x_python_type_nested_imports(output_file: Path) -> None:
"""Test x-python-type with nested types that require imports (e.g., Callable[[Iterable[str]], str])."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "x_python_type_nested_imports.json",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
extra_args=["--output-model-type", "typing.TypedDict"],
)


def test_x_python_type_nested_unknown_type(output_file: Path) -> None:
"""Test x-python-type with nested types not in PYTHON_TYPE_IMPORTS (e.g., MyCustomType)."""
run_main_and_assert(
input_path=JSON_SCHEMA_DATA_PATH / "x_python_type_nested_unknown_type.json",
output_path=output_file,
input_file_type=None,
assert_func=assert_file_content,
extra_args=["--output-model-type", "typing.TypedDict"],
)
Loading