-
-
Notifications
You must be signed in to change notification settings - Fork 437
Add pydantic_v2.dataclass output type and remove pydantic v1 dataclass #2746
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
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
e0e638c
Add pydantic_v2.dataclass output type and remove pydantic v1 dataclass
koxudaxi 5b3fe5b
Fix formatting issues
koxudaxi e02b990
Remove line comments and add e2e tests for nested models and constraints
koxudaxi d6d580c
Add e2e tests for Field constraints, defaults, and enum types
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
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 was deleted.
Oops, something went wrong.
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
152 changes: 152 additions & 0 deletions
152
src/datamodel_code_generator/model/pydantic_v2/dataclass.py
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,152 @@ | ||
| """Pydantic v2 dataclass model generator. | ||
|
|
||
| Generates pydantic.dataclasses.dataclass decorated classes with validation support. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import TYPE_CHECKING, Any, ClassVar | ||
|
|
||
| from datamodel_code_generator.model import DataModel, DataModelFieldBase | ||
| from datamodel_code_generator.model.base import UNDEFINED | ||
| from datamodel_code_generator.model.dataclass import has_field_assignment | ||
| from datamodel_code_generator.model.pydantic_v2.base_model import Constraints | ||
| from datamodel_code_generator.model.pydantic_v2.base_model import ( | ||
| DataModelField as DataModelFieldV2, | ||
| ) | ||
| from datamodel_code_generator.model.pydantic_v2.imports import ( | ||
| IMPORT_CONFIG_DICT, | ||
| IMPORT_PYDANTIC_DATACLASS, | ||
| ) | ||
| from datamodel_code_generator.reference import Reference | ||
|
|
||
| if TYPE_CHECKING: | ||
| from collections import defaultdict | ||
| from pathlib import Path | ||
|
|
||
| from datamodel_code_generator import DataclassArguments | ||
| from datamodel_code_generator.imports import Import | ||
|
|
||
|
|
||
| class DataClass(DataModel): | ||
| """DataModel implementation for Pydantic v2 dataclasses.""" | ||
|
|
||
| TEMPLATE_FILE_PATH: ClassVar[str] = "pydantic_v2/dataclass.jinja2" | ||
| DEFAULT_IMPORTS: ClassVar[tuple[Import, ...]] = (IMPORT_PYDANTIC_DATACLASS,) | ||
| SUPPORTS_DISCRIMINATOR: ClassVar[bool] = True | ||
| SUPPORTS_KW_ONLY: ClassVar[bool] = True | ||
|
|
||
| def __init__( # noqa: PLR0913 | ||
| self, | ||
| *, | ||
| reference: Reference, | ||
| fields: list[DataModelFieldBase], | ||
| decorators: list[str] | None = None, | ||
| base_classes: list[Reference] | None = None, | ||
| custom_base_class: str | None = None, | ||
| custom_template_dir: Path | None = None, | ||
| extra_template_data: defaultdict[str, dict[str, Any]] | None = None, | ||
| methods: list[str] | None = None, | ||
| path: Path | None = None, | ||
| description: str | None = None, | ||
| default: Any = UNDEFINED, | ||
| nullable: bool = False, | ||
| keyword_only: bool = False, | ||
| frozen: bool = False, | ||
| treat_dot_as_module: bool | None = None, | ||
| dataclass_arguments: DataclassArguments | None = None, | ||
| ) -> None: | ||
| """Initialize pydantic v2 dataclass with sorted fields and ConfigDict support.""" | ||
| super().__init__( | ||
| reference=reference, | ||
| fields=sorted(fields, key=has_field_assignment), | ||
| decorators=decorators, | ||
| base_classes=base_classes, | ||
| custom_base_class=custom_base_class, | ||
| custom_template_dir=custom_template_dir, | ||
| extra_template_data=extra_template_data, | ||
| methods=methods, | ||
| path=path, | ||
| description=description, | ||
| default=default, | ||
| nullable=nullable, | ||
| keyword_only=keyword_only, | ||
| frozen=frozen, | ||
| treat_dot_as_module=treat_dot_as_module, | ||
| ) | ||
|
|
||
| if dataclass_arguments is not None: | ||
| self.dataclass_arguments = dataclass_arguments | ||
| else: | ||
| self.dataclass_arguments = {} | ||
| if frozen: | ||
| self.dataclass_arguments["frozen"] = True | ||
| if keyword_only: | ||
| self.dataclass_arguments["kw_only"] = True | ||
|
|
||
| config_parameters: dict[str, Any] = {} | ||
|
|
||
| extra = self._get_config_extra() | ||
| if extra: | ||
| config_parameters["extra"] = extra | ||
|
|
||
| if self.extra_template_data.get("use_attribute_docstrings"): | ||
| config_parameters["use_attribute_docstrings"] = True | ||
|
|
||
| for data_type in self.all_data_types: | ||
| if data_type.is_custom_type: # pragma: no cover | ||
| config_parameters["arbitrary_types_allowed"] = True | ||
| break | ||
|
|
||
| if config_parameters: | ||
| self._additional_imports.append(IMPORT_CONFIG_DICT) | ||
| self.extra_template_data["config"] = config_parameters | ||
|
|
||
| def _get_config_extra(self) -> str | None: | ||
| """Get extra field configuration for ConfigDict.""" | ||
| additional_properties = self.extra_template_data.get("additionalProperties") | ||
| allow_extra_fields = self.extra_template_data.get("allow_extra_fields") | ||
| extra_fields = self.extra_template_data.get("extra_fields") | ||
|
|
||
| if allow_extra_fields or extra_fields == "allow": | ||
| return "'allow'" | ||
| if extra_fields == "forbid": | ||
| return "'forbid'" | ||
| if extra_fields == "ignore": | ||
| return "'ignore'" | ||
| if additional_properties is True: | ||
| return "'allow'" | ||
| if additional_properties is False: | ||
| return "'forbid'" | ||
| return None | ||
|
|
||
| def create_reuse_model(self, base_ref: Reference) -> DataClass: | ||
| """Create inherited model with empty fields pointing to base reference.""" | ||
| return self.__class__( | ||
| fields=[], | ||
| base_classes=[base_ref], | ||
| description=self.description, | ||
| reference=Reference( | ||
| name=self.name, | ||
| path=self.reference.path + "/reuse", | ||
| ), | ||
| custom_template_dir=self._custom_template_dir, | ||
| custom_base_class=self.custom_base_class, | ||
| keyword_only=self.keyword_only, | ||
| frozen=self.frozen, | ||
| treat_dot_as_module=self._treat_dot_as_module, | ||
| dataclass_arguments=self.dataclass_arguments, | ||
| ) | ||
|
|
||
|
|
||
| class DataModelField(DataModelFieldV2): | ||
| """Field implementation for Pydantic v2 dataclass models. | ||
|
|
||
| Inherits pydantic v2 Field() constraint handling from DataModelFieldV2. | ||
| """ | ||
|
|
||
| constraints: Constraints | None = None # pyright: ignore[reportIncompatibleVariableOverride] | ||
|
|
||
| def process_const(self) -> None: | ||
| """Process const field constraint using literal type.""" | ||
| self._process_const_as_literal() | ||
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
37 changes: 0 additions & 37 deletions
37
src/datamodel_code_generator/model/template/pydantic/dataclass.jinja2
This file was deleted.
Oops, something went wrong.
61 changes: 61 additions & 0 deletions
61
src/datamodel_code_generator/model/template/pydantic_v2/dataclass.jinja2
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 @@ | ||
| {% for decorator in decorators -%} | ||
| {{ decorator }} | ||
| {% endfor -%} | ||
| {%- set args = [] %} | ||
| {%- for k, v in (dataclass_arguments or {}).items() %} | ||
| {%- if v is not none and v is not false %} | ||
| {%- set _ = args.append(k ~ '=' ~ (v|pprint)) %} | ||
| {%- endif %} | ||
| {%- endfor %} | ||
| {%- if config %} | ||
| {%- set config_items = [] %} | ||
| {%- for k, v in config.items() %} | ||
| {%- set _ = config_items.append(k ~ '=' ~ v) %} | ||
| {%- endfor %} | ||
| {%- set _ = args.append('config=ConfigDict(' ~ config_items | join(', ') ~ ')') %} | ||
| {%- endif %} | ||
| {%- if args %} | ||
| @dataclass({{ args | join(', ') }}) | ||
| {%- else %} | ||
| @dataclass | ||
| {%- endif %} | ||
| {%- if base_class %} | ||
| class {{ class_name }}({{ base_class }}): | ||
| {%- else %} | ||
| class {{ class_name }}: | ||
| {%- endif %} | ||
| {%- if description %} | ||
| """ | ||
| {{ description | indent(4) }} | ||
| """ | ||
| {%- endif %} | ||
| {%- if not fields and not description %} | ||
| pass | ||
| {%- endif %} | ||
| {%- for field in fields -%} | ||
| {%- if not field.annotated and field.field %} | ||
| {{ field.name }}: {{ field.type_hint }} = {{ field.field }} | ||
| {%- else %} | ||
| {%- if field.annotated %} | ||
| {{ field.name }}: {{ field.annotated }} | ||
| {%- else %} | ||
| {{ field.name }}: {{ field.type_hint }} | ||
| {%- endif %} | ||
| {%- if not field.has_default_factory_in_field and not field.required and (field.represented_default != 'None' or not field.strip_default_none or field.data_type.is_optional) | ||
| %} = {{ field.represented_default }} | ||
| {%- endif -%} | ||
| {%- endif %} | ||
| {%- if field.docstring %} | ||
| """ | ||
| {{ field.docstring | indent(4) }} | ||
| """ | ||
| {%- if field.use_inline_field_description and not loop.last %} | ||
|
|
||
| {% endif %} | ||
| {%- elif field.inline_field_docstring %} | ||
| {{ field.inline_field_docstring }} | ||
| {%- if not loop.last %} | ||
|
|
||
| {% endif %} | ||
| {%- endif %} | ||
| {%- endfor -%} |
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
12 changes: 12 additions & 0 deletions
12
tests/data/expected/main/jsonschema/generate_pydantic_v2_dataclass.py
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,12 @@ | ||
| # generated by datamodel-codegen: | ||
| # filename: simple_string.json | ||
| # timestamp: 2019-07-26T00:00:00+00:00 | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from pydantic.dataclasses import dataclass | ||
|
|
||
|
|
||
| @dataclass | ||
| class Model: | ||
| s: str |
13 changes: 13 additions & 0 deletions
13
tests/data/expected/main/jsonschema/pydantic_v2_dataclass_additional_props_true.py
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,13 @@ | ||
| # generated by datamodel-codegen: | ||
| # filename: pydantic_v2_dataclass_additional_props_true.json | ||
| # timestamp: 2019-07-26T00:00:00+00:00 | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from pydantic import ConfigDict | ||
| from pydantic.dataclasses import dataclass | ||
|
|
||
|
|
||
| @dataclass(config=ConfigDict(extra='allow')) | ||
| class Model: | ||
| s: str |
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.