-
-
Notifications
You must be signed in to change notification settings - Fork 437
Add dynamic model generation support #2898
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
fe25d68
Add dynamic model generation support
koxudaxi 018c6af
Simplify dynamic module and improve coverage
koxudaxi e739d42
Add more tests for dynamic module coverage
koxudaxi 242d46e
Remove unused code and fix function-level imports
koxudaxi 8ff7e05
Remove inline comments and move imports to top level
koxudaxi 9db7735
Remove line comments and fix description access bug
koxudaxi 8ab5951
Refactor tests: use external files and inline-snapshot
koxudaxi 0e0a9e4
Simplify type_resolver: use builtins for primitive types
koxudaxi e794006
Add container type handling in TypeResolver
koxudaxi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| """Dynamic model generation module. | ||
|
|
||
| This module provides functionality to generate actual Python model classes | ||
| at runtime using Pydantic's create_model(), instead of generating text code. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from datamodel_code_generator.dynamic.creator import DynamicModelCreator | ||
| from datamodel_code_generator.dynamic.exceptions import ( | ||
| DynamicModelError, | ||
| TypeResolutionError, | ||
| ) | ||
|
|
||
| __all__ = [ | ||
| "DynamicModelCreator", | ||
| "DynamicModelError", | ||
| "TypeResolutionError", | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| """Constraint conversion utilities for dynamic model generation.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import TYPE_CHECKING, Any | ||
|
|
||
| from datamodel_code_generator.util import model_dump | ||
|
|
||
| if TYPE_CHECKING: | ||
| from datamodel_code_generator.model.base import ConstraintsBase | ||
|
|
||
|
|
||
| CONSTRAINT_FIELD_MAP: dict[str, str] = { | ||
| "ge": "ge", | ||
| "gt": "gt", | ||
| "le": "le", | ||
| "lt": "lt", | ||
| "multiple_of": "multiple_of", | ||
| "min_length": "min_length", | ||
| "max_length": "max_length", | ||
| "regex": "pattern", | ||
| "pattern": "pattern", | ||
| "min_items": "min_length", | ||
| "max_items": "max_length", | ||
| } | ||
|
|
||
| JSON_SCHEMA_EXTRA_FIELDS: frozenset[str] = frozenset({ | ||
| "unique_items", | ||
| "min_properties", | ||
| "max_properties", | ||
| }) | ||
|
|
||
|
|
||
| def constraints_to_field_kwargs( | ||
| constraints: ConstraintsBase | None, | ||
| ) -> dict[str, Any]: | ||
| """Convert DataModel constraints to Pydantic Field kwargs.""" | ||
| if constraints is None: | ||
| return {} | ||
|
|
||
| kwargs: dict[str, Any] = {} | ||
| json_schema_extra: dict[str, Any] = {} | ||
|
|
||
| for field_name, value in model_dump(constraints).items(): | ||
| if value is None: | ||
| continue | ||
|
|
||
| if field_name in CONSTRAINT_FIELD_MAP: | ||
| kwargs[CONSTRAINT_FIELD_MAP[field_name]] = value | ||
| elif field_name in JSON_SCHEMA_EXTRA_FIELDS: | ||
| json_schema_extra[_to_camel_case(field_name)] = value | ||
|
|
||
| if json_schema_extra: | ||
| kwargs["json_schema_extra"] = json_schema_extra | ||
|
|
||
| return kwargs | ||
|
|
||
|
|
||
| def _to_camel_case(snake_str: str) -> str: | ||
| """Convert snake_case to camelCase.""" | ||
| components = snake_str.split("_") | ||
| return components[0] + "".join(x.title() for x in components[1:]) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,185 @@ | ||
| """Dynamic model creator for generating Python classes at runtime.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from enum import Enum | ||
| from typing import TYPE_CHECKING, Any, cast | ||
|
|
||
| from pydantic import BaseModel, Field, create_model | ||
|
|
||
| from datamodel_code_generator.dynamic.constraints import constraints_to_field_kwargs | ||
|
|
||
| from datamodel_code_generator.dynamic.exceptions import TypeResolutionError | ||
|
|
||
| from datamodel_code_generator.dynamic.type_resolver import TypeResolver | ||
|
|
||
| from datamodel_code_generator.model.enum import Enum as EnumModel | ||
|
|
||
| from datamodel_code_generator.parser.base import sort_data_models | ||
|
|
||
|
|
||
| if TYPE_CHECKING: | ||
| from pydantic.fields import FieldInfo | ||
|
|
||
| from datamodel_code_generator.model.base import DataModel, DataModelFieldBase | ||
|
|
||
| from datamodel_code_generator.parser.base import Parser | ||
|
|
||
|
|
||
|
|
||
| class DynamicModelCreator: | ||
| """Creates actual Python classes from DataModel objects.""" | ||
|
|
||
| def __init__(self, parser: Parser) -> None: | ||
| """Initialize with a parser instance.""" | ||
| self.parser = parser | ||
| self._models: dict[str, type[Any]] = {} | ||
| self._short_name_lookup: dict[str, type[Any]] = {} | ||
| self._type_resolver = TypeResolver(self._short_name_lookup) | ||
|
|
||
| def create_models(self) -> dict[str, type]: | ||
| """Create all models from parser results. | ||
|
|
||
| Returns: | ||
| Dictionary mapping class names to actual Python classes. | ||
|
|
||
| Raises: | ||
| TypeResolutionError: If a type cannot be resolved. | ||
| DynamicModelError: If model generation fails. | ||
| """ | ||
| if not self.parser.results: | ||
| return {} | ||
|
|
||
| _, sorted_models_dict, _ = sort_data_models(self.parser.results) | ||
|
|
||
| for data_model in sorted_models_dict.values(): | ||
| if isinstance(data_model, EnumModel): | ||
| self._create_enum_model(data_model) | ||
| else: | ||
| self._create_pydantic_model(data_model) | ||
|
|
||
| self._rebuild_models() | ||
|
|
||
| return self._models | ||
|
|
||
| def _create_pydantic_model(self, data_model: DataModel) -> type[Any]: | ||
| """Create a single Pydantic model from DataModel.""" | ||
| field_definitions: dict[str, tuple[Any, FieldInfo]] = {} | ||
|
|
||
| for field in data_model.fields: | ||
| if field.name is None: | ||
| continue | ||
|
|
||
| try: | ||
| field_type, type_constraints = self._type_resolver.resolve_with_constraints(field.data_type) | ||
| except Exception as e: | ||
| raise TypeResolutionError(field.data_type, data_model.class_name, field.name or "") from e | ||
|
|
||
| field_info = self._create_field_info(field, type_constraints) | ||
| field_definitions[field.name] = (field_type, field_info) | ||
|
|
||
| base_classes = self._resolve_base_classes(data_model) | ||
| module_name = self._get_module_name(data_model) | ||
|
|
||
| if len(base_classes) > 1: | ||
| combined_base_name = f"_{data_model.class_name}Base" | ||
| combined_base = type(combined_base_name, base_classes, {}) | ||
| effective_base: type[Any] = combined_base | ||
| else: | ||
| effective_base = base_classes[0] if base_classes else BaseModel | ||
|
|
||
| model = cast( | ||
| "type[Any]", | ||
| create_model( | ||
| data_model.class_name, | ||
| __base__=effective_base, | ||
| __module__=module_name, | ||
| **cast("dict[str, Any]", field_definitions), | ||
| ), | ||
| ) | ||
|
|
||
| model_key = self._get_model_key(data_model) | ||
| self._models[model_key] = model | ||
| self._short_name_lookup[data_model.class_name] = model | ||
|
|
||
| if model_key != data_model.class_name: | ||
| self._models[data_model.class_name] = model | ||
|
|
||
| return model | ||
|
|
||
| def _get_model_key(self, data_model: DataModel) -> str: | ||
| """Get module-qualified key for model storage.""" | ||
| module_name = self._get_module_name(data_model) | ||
| if module_name and module_name != "__dynamic__": | ||
| return f"{module_name}.{data_model.class_name}" | ||
| return data_model.class_name | ||
|
|
||
| @staticmethod | ||
| def _create_field_info(field: DataModelFieldBase, type_constraints: dict[str, Any] | None = None) -> FieldInfo: | ||
| """Convert DataModelFieldBase to Pydantic FieldInfo.""" | ||
| kwargs = constraints_to_field_kwargs(field.constraints) | ||
|
|
||
| if type_constraints: | ||
| kwargs.update(type_constraints) | ||
|
|
||
| if (hasattr(field, "has_default") and field.has_default) or field.default is not None: | ||
| kwargs["default"] = field.default | ||
| elif (default_factory := getattr(field, "default_factory", None)) is not None: | ||
| kwargs["default_factory"] = default_factory | ||
| elif field.required: | ||
| kwargs["default"] = ... | ||
| else: | ||
| kwargs["default"] = None | ||
|
|
||
| if field.alias: | ||
| kwargs["alias"] = field.alias | ||
|
|
||
| description = field.extras.get("description") | ||
| if description: | ||
| kwargs["description"] = description | ||
|
|
||
| return Field(**kwargs) | ||
|
|
||
| def _resolve_base_classes(self, data_model: DataModel) -> tuple[type, ...]: | ||
| """Resolve base classes for the model.""" | ||
| if not data_model.base_classes: | ||
| return (BaseModel,) | ||
|
|
||
| bases = [] | ||
| for base_class in data_model.base_classes: | ||
| if base_class.reference and base_class.reference.short_name in self._short_name_lookup: | ||
| bases.append(self._short_name_lookup[base_class.reference.short_name]) | ||
| else: | ||
| bases.append(BaseModel) | ||
|
|
||
| return tuple(bases) if bases else (BaseModel,) | ||
|
|
||
| @staticmethod | ||
| def _get_module_name(data_model: DataModel) -> str: | ||
| """Determine module name for the dynamic model.""" | ||
| if data_model.reference and data_model.reference.path: | ||
| parts = data_model.reference.path.split("/") | ||
| return ".".join(p for p in parts if p and p != "#") | ||
| return "__dynamic__" | ||
|
|
||
| def _create_enum_model(self, data_model: DataModel) -> type[Any]: | ||
| """Create an Enum class from DataModel.""" | ||
| members = {} | ||
| for field in data_model.fields: | ||
| if field.name and field.default is not None: | ||
| value = field.default | ||
| if isinstance(value, str): | ||
| value = value.strip("'\"") | ||
| members[field.name] = value | ||
|
|
||
| enum_class: type[Any] = Enum(data_model.class_name, members) | ||
|
|
||
| model_key = self._get_model_key(data_model) | ||
| self._models[model_key] = enum_class | ||
| self._short_name_lookup[data_model.class_name] = enum_class | ||
|
|
||
| if model_key != data_model.class_name: | ||
| self._models[data_model.class_name] = enum_class | ||
|
|
||
| return enum_class | ||
|
|
||
| def _rebuild_models(self) -> None: | ||
| """Resolve forward references by calling model_rebuild() on all models.""" | ||
| namespace = {**self._short_name_lookup} | ||
|
|
||
| for model in self._models.values(): | ||
| if isinstance(model, type) and issubclass(model, BaseModel): | ||
| model.model_rebuild(_types_namespace=namespace) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| """Custom exceptions for dynamic model generation.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import TYPE_CHECKING | ||
|
|
||
| if TYPE_CHECKING: | ||
| from datamodel_code_generator.types import DataType | ||
|
|
||
|
|
||
|
|
||
| class DynamicModelError(Exception): | ||
| """Base exception for dynamic model generation.""" | ||
|
|
||
|
|
||
| class TypeResolutionError(DynamicModelError): | ||
| """Failed to resolve a type to a Python type object.""" | ||
|
|
||
| def __init__(self, type_info: DataType, model_name: str, field_name: str) -> None: | ||
| """Initialize with type info and context.""" | ||
| self.type_info = type_info | ||
| self.model_name = model_name | ||
| self.field_name = field_name | ||
| super().__init__(f"Cannot resolve type for field '{field_name}' in model '{model_name}': {type_info}") | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.