88
99import enum as _enum
1010import json
11+ import re
1112from collections import defaultdict
1213from collections .abc import Iterable
1314from contextlib import contextmanager , suppress
@@ -1334,6 +1335,13 @@ def _is_compatible_python_type(self, schema_type: str | None, python_type: str)
13341335 compatible = self .COMPATIBLE_PYTHON_TYPES .get (schema_type , frozenset ())
13351336 return base_type in compatible
13361337
1338+ def _extract_all_type_names (self , type_str : str ) -> list [str ]: # noqa: PLR6301
1339+ """Extract all type names from a type annotation string."""
1340+ # Match type names: word characters starting with uppercase, not preceded by a dot
1341+ # This handles cases like Callable[[Iterable[str]], str]
1342+ pattern = r"(?<![.\w])([A-Z]\w*)"
1343+ return re .findall (pattern , type_str )
1344+
13371345 def _get_python_type_override (self , obj : JsonSchemaObject ) -> DataType | None :
13381346 """Get DataType from x-python-type if it's incompatible with schema type."""
13391347 x_python_type = obj .extras .get ("x-python-type" )
@@ -1357,7 +1365,18 @@ def _get_python_type_override(self, obj: JsonSchemaObject) -> DataType | None:
13571365 # If not in predefined imports, create import from the full path
13581366 import_ = Import .from_full_path (prefix )
13591367
1360- return self .data_type (type = type_str , import_ = import_ )
1368+ # Collect imports for all nested types (e.g., Iterable inside Callable[[Iterable[str]], str])
1369+ nested_imports : list [DataType ] = []
1370+ for type_name in self ._extract_all_type_names (type_str ):
1371+ if type_name != base_type :
1372+ nested_import = self .PYTHON_TYPE_IMPORTS .get (type_name )
1373+ if nested_import :
1374+ nested_imports .append (self .data_type (import_ = nested_import ))
1375+
1376+ result = self .data_type (type = type_str , import_ = import_ )
1377+ if nested_imports :
1378+ result .data_types .extend (nested_imports )
1379+ return result
13611380
13621381 def _apply_title_as_name (self , name : str , obj : JsonSchemaObject ) -> str :
13631382 """Apply title as name if use_title_as_name is enabled."""
0 commit comments