Remove pydantic v1 runtime compat layer#3025
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR removes Pydantic v1 branching across code and CI, unifies models and validators to Pydantic v2 APIs (ConfigDict, .model_validate, .model_dump, field/model validators), updates configuration and parser internals to v2 idioms, and removes pydantic1-specific tests and CI matrix entries. Changes
Sequence Diagram(s)sequenceDiagram
participant CLI as CLI (user)
participant Config as Config (model_validate)
participant Parser as Parser
participant SchemaModel as JsonSchema/OpenAPI Model
participant Generator as Code Generator / Output
CLI->>Config: parse args / files
Config->>Config: model_validate(options) (ConfigDict / validators)
Config->>Parser: provide parser/config options
Parser->>SchemaModel: SchemaModel.model_validate(raw schema)
SchemaModel->>Parser: .model_dump() normalized schema
Parser->>Generator: generate code from normalized schema
Generator->>CLI: return files / exit status
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
📚 Docs Preview: https://pr-3025.datamodel-code-generator.pages.dev |
Merging this PR will not alter performance
|
🤖 Generated by GitHub Actions
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #3025 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 95 95
Lines 18389 18165 -224
Branches 2129 2097 -32
==========================================
- Hits 18389 18165 -224
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/datamodel_code_generator/validators.py (1)
37-38: Clean up staleValidatorsConfig is Nonecompatibility branch in call sites.Since Line 37 now guarantees
ValidatorsConfigis always defined, theif ValidatorsConfig is Nonecheck insrc/datamodel_code_generator/__main__.py:843is dead code and keeps obsolete v1 messaging.Suggested follow-up diff in
src/datamodel_code_generator/__main__.py- if ValidatorsConfig is None: - return None, "--validators option requires Pydantic v2. Please upgrade to Pydantic v2 or remove the option." - with file_handle as data: try: raw = json.load(data)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/datamodel_code_generator/validators.py` around lines 37 - 38, Remove the dead compatibility branch that checks "if ValidatorsConfig is None" in src/datamodel_code_generator/__main__.py (around the code path that references ValidatorsConfig when building/validating models); since ValidatorsConfig is now always defined (class ValidatorsConfig in validators.py), delete the conditional and its obsolete v1 messaging and simplify the flow to unconditionally use ValidatorsConfig (update any related log/error text to remove v1 compatibility wording).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/datamodel_code_generator/__main__.py`:
- Around line 150-152: Config.__getitem__ currently delegates to get() which
raises AttributeError for missing keys, violating mapping semantics; update
Config.__getitem__ to catch AttributeError from self.get(item) and re-raise a
KeyError(item) (preserving the original exception as the __cause__) so consumers
receive KeyError for missing keys; reference the Config.__getitem__ and get
methods when making the change.
---
Nitpick comments:
In `@src/datamodel_code_generator/validators.py`:
- Around line 37-38: Remove the dead compatibility branch that checks "if
ValidatorsConfig is None" in src/datamodel_code_generator/__main__.py (around
the code path that references ValidatorsConfig when building/validating models);
since ValidatorsConfig is now always defined (class ValidatorsConfig in
validators.py), delete the conditional and its obsolete v1 messaging and
simplify the flow to unconditionally use ValidatorsConfig (update any related
log/error text to remove v1 compatibility wording).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 0ab264d0-14e0-4070-b8d2-fb894c80cab1
📒 Files selected for processing (21)
.github/workflows/test.yamlpyproject.tomlsrc/datamodel_code_generator/__init__.pysrc/datamodel_code_generator/__main__.pysrc/datamodel_code_generator/config.pysrc/datamodel_code_generator/input_model.pysrc/datamodel_code_generator/model/base.pysrc/datamodel_code_generator/model/msgspec.pysrc/datamodel_code_generator/model/pydantic_v2/__init__.pysrc/datamodel_code_generator/model/pydantic_v2/base_model.pysrc/datamodel_code_generator/parser/base.pysrc/datamodel_code_generator/parser/jsonschema.pysrc/datamodel_code_generator/parser/openapi.pysrc/datamodel_code_generator/reference.pysrc/datamodel_code_generator/types.pysrc/datamodel_code_generator/validators.pytests/main/test_main_general.pytests/parser/test_jsonschema.pytests/parser/test_openapi.pytests/test_input_model.pytox.ini
💤 Files with no reviewable changes (4)
- .github/workflows/test.yaml
- tox.ini
- tests/test_input_model.py
- pyproject.toml
There was a problem hiding this comment.
♻️ Duplicate comments (1)
src/datamodel_code_generator/__main__.py (1)
146-152:⚠️ Potential issue | 🟡 Minor
__getitem__should raiseKeyErrorfor missing keys.At Line 152,
__getitem__forwards togetattr()viaget(), so missing fields raiseAttributeErrorinstead ofKeyError, which breaks mapping-like behavior.Suggested fix
- def __getitem__(self, item: str) -> Any: # pragma: no cover - """Get item by key.""" - return self.get(item) # ty: ignore + def __getitem__(self, item: str) -> Any: # pragma: no cover + """Get item by key.""" + try: + return getattr(self, item) + except AttributeError as exc: + raise KeyError(item) from exc🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/datamodel_code_generator/__main__.py` around lines 146 - 152, The __getitem__ currently delegates to get/getattr which causes AttributeError for missing keys; change __getitem__(self, item: str) to attempt to return the attribute (e.g., via getattr or calling get) but catch AttributeError (or check with hasattr) and raise KeyError(item) instead (use "raise KeyError(item) from None" if preserving exception chaining is desired); update the __getitem__ implementation in the class that defines get and __getitem__ accordingly so mapping-like access raises KeyError for absent keys.
🧹 Nitpick comments (1)
tests/main/test_public_api_signature_baseline.py (1)
38-40: Consider removingPYDANTIC_V2_SKIPand related decorators.Since this PR removes Pydantic v1 support, the
PYDANTIC_V2_SKIPmarker andis_pydantic_v2import become effectively dead code—is_pydantic_v2()will always returnTrue. The tests decorated with@PYDANTIC_V2_SKIP(lines 577, 588, 602, 613, 624, 638, 652, 669, 689, 706) will never be skipped.Consider removing these decorators and the import for consistency with the unconditional execution in
test_generate_signature_matches_baselineandtest_parser_signature_matches_baseline.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/main/test_public_api_signature_baseline.py` around lines 38 - 40, Remove the now-dead Pydantic v2 skip machinery: delete the import "is_pydantic_v2" and the PYDANTIC_V2_SKIP assignment, and remove all usages of the `@PYDANTIC_V2_SKIP` decorator from the tests (including the decorators applied near test_generate_signature_matches_baseline and test_parser_signature_matches_baseline); this cleans up the unused symbol PYDANTIC_V2_SKIP and the never-false is_pydantic_v2() check.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@src/datamodel_code_generator/__main__.py`:
- Around line 146-152: The __getitem__ currently delegates to get/getattr which
causes AttributeError for missing keys; change __getitem__(self, item: str) to
attempt to return the attribute (e.g., via getattr or calling get) but catch
AttributeError (or check with hasattr) and raise KeyError(item) instead (use
"raise KeyError(item) from None" if preserving exception chaining is desired);
update the __getitem__ implementation in the class that defines get and
__getitem__ accordingly so mapping-like access raises KeyError for absent keys.
---
Nitpick comments:
In `@tests/main/test_public_api_signature_baseline.py`:
- Around line 38-40: Remove the now-dead Pydantic v2 skip machinery: delete the
import "is_pydantic_v2" and the PYDANTIC_V2_SKIP assignment, and remove all
usages of the `@PYDANTIC_V2_SKIP` decorator from the tests (including the
decorators applied near test_generate_signature_matches_baseline and
test_parser_signature_matches_baseline); this cleans up the unused symbol
PYDANTIC_V2_SKIP and the never-false is_pydantic_v2() check.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: afc57a34-9af2-4afd-86ca-185f936edf66
📒 Files selected for processing (3)
src/datamodel_code_generator/__main__.pytests/main/jsonschema/test_main_jsonschema.pytests/main/test_public_api_signature_baseline.py
💤 Files with no reviewable changes (1)
- tests/main/jsonschema/test_main_jsonschema.py
There was a problem hiding this comment.
♻️ Duplicate comments (1)
src/datamodel_code_generator/__main__.py (1)
146-152:⚠️ Potential issue | 🟡 Minor
Config.__getitem__should raiseKeyErrorfor missing keys.The
__getitem__method delegates toget(), which usesgetattr(). For missing attributes, this raisesAttributeErrorinstead ofKeyError, breaking standard mapping semantics.Suggested fix
- def get(self, item: str) -> Any: + def get(self, item: str, default: Any = None) -> Any: """Get attribute value by name.""" - return getattr(self, item) + return getattr(self, item, default) def __getitem__(self, item: str) -> Any: """Get item by key.""" - return self.get(item) # ty: ignore + try: + return getattr(self, item) + except AttributeError as exc: + raise KeyError(item) from exc🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/datamodel_code_generator/__main__.py` around lines 146 - 152, Config.__getitem__ currently delegates to get() which uses getattr() and lets AttributeError bubble up; change __getitem__ to catch AttributeError (or check existence with hasattr) and raise KeyError for missing keys so it follows mapping semantics: inside Config.__getitem__ (and/or adjust Config.get signature to accept a default), attempt to retrieve the attribute via getattr(self, item) in a try/except and convert any AttributeError into KeyError(f"{item}") so callers receive a KeyError for missing keys instead of AttributeError.
🧹 Nitpick comments (1)
src/datamodel_code_generator/__main__.py (1)
399-417: Consider moving the import outside the class.Re-importing
field_validatoras_field_validatorinside the class body (Line 399) is unusual. This could be moved to the module-level imports for consistency and clarity.Suggested refactor
Move the import to line 49 with the other pydantic imports, and use
field_validatordirectly:-from pydantic import BaseModel, ConfigDict, ValidationError, field_validator, model_validator +from pydantic import BaseModel, ConfigDict, ValidationError, field_validator, model_validator # Inside Config class, remove: - from pydantic import field_validator as _field_validator # noqa: PLC0415 - - `@_field_validator`("input_model", mode="before") + `@field_validator`("input_model", mode="before") `@classmethod` def coerce_input_model_to_list(cls, v: str | list[str] | None) -> list[str] | None: ... - `@_field_validator`("class_name_affix_scope", mode="before") + `@field_validator`("class_name_affix_scope", mode="before") `@classmethod` def validate_class_name_affix_scope(cls, v: str | ClassNameAffixScope | None) -> ClassNameAffixScope: ...🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/datamodel_code_generator/__main__.py` around lines 399 - 417, Move the local import "from pydantic import field_validator as _field_validator" out of the class body and into the module-level imports (alongside other pydantic imports) and use the canonical name "field_validator" in the decorators; update the decorators on the methods coerce_input_model_to_list and validate_class_name_affix_scope to use `@field_validator`(...) instead of `@_field_validator`, removing the in-class import and keeping the methods' signatures and behavior unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@src/datamodel_code_generator/__main__.py`:
- Around line 146-152: Config.__getitem__ currently delegates to get() which
uses getattr() and lets AttributeError bubble up; change __getitem__ to catch
AttributeError (or check existence with hasattr) and raise KeyError for missing
keys so it follows mapping semantics: inside Config.__getitem__ (and/or adjust
Config.get signature to accept a default), attempt to retrieve the attribute via
getattr(self, item) in a try/except and convert any AttributeError into
KeyError(f"{item}") so callers receive a KeyError for missing keys instead of
AttributeError.
---
Nitpick comments:
In `@src/datamodel_code_generator/__main__.py`:
- Around line 399-417: Move the local import "from pydantic import
field_validator as _field_validator" out of the class body and into the
module-level imports (alongside other pydantic imports) and use the canonical
name "field_validator" in the decorators; update the decorators on the methods
coerce_input_model_to_list and validate_class_name_affix_scope to use
`@field_validator`(...) instead of `@_field_validator`, removing the in-class import
and keeping the methods' signatures and behavior unchanged.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 248b2227-1064-44f4-bcea-288522eb2caa
📒 Files selected for processing (6)
src/datamodel_code_generator/__main__.pysrc/datamodel_code_generator/model/base.pysrc/datamodel_code_generator/parser/jsonschema.pysrc/datamodel_code_generator/parser/openapi.pysrc/datamodel_code_generator/reference.pysrc/datamodel_code_generator/types.py
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
src/datamodel_code_generator/__main__.py (1)
146-152:⚠️ Potential issue | 🟡 Minor
Config.__getitem__still leaksAttributeErrorfor missing keys.That breaks normal mapping semantics for callers expecting
KeyErroron absent entries.Suggested fix
def __getitem__(self, item: str) -> Any: # pragma: no cover """Get item by key.""" - return self.get(item) # ty: ignore + try: + return getattr(self, item) + except AttributeError as exc: + raise KeyError(item) from exc🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/datamodel_code_generator/__main__.py` around lines 146 - 152, The Config.__getitem__ currently forwards to get which uses getattr and therefore propagates AttributeError for missing attributes; change this so missing keys raise KeyError like a mapping: modify either Config.get or Config.__getitem__ (referencing method names get and __getitem__ on class Config) to detect a missing attribute (use getattr with a sentinel/default or catch AttributeError) and raise KeyError(item) instead of letting AttributeError bubble up.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/datamodel_code_generator/reference.py`:
- Around line 96-113: The dict() wrapper currently coerces exclude into a set
which destroys nested mappings; update dict() (the method calling
self.model_dump) to preserve mapping form: detect if the incoming exclude is a
Mapping and if so merge it with self._exclude_fields by copying the mapping and
adding any names from self._exclude_fields as keys with a True value (so
top-level excluded names remain excluded) then pass that merged mapping to
model_dump; if exclude is not a Mapping, keep the existing behavior of unioning
set(exclude or ()) with self._exclude_fields and pass that set to model_dump.
---
Duplicate comments:
In `@src/datamodel_code_generator/__main__.py`:
- Around line 146-152: The Config.__getitem__ currently forwards to get which
uses getattr and therefore propagates AttributeError for missing attributes;
change this so missing keys raise KeyError like a mapping: modify either
Config.get or Config.__getitem__ (referencing method names get and __getitem__
on class Config) to detect a missing attribute (use getattr with a
sentinel/default or catch AttributeError) and raise KeyError(item) instead of
letting AttributeError bubble up.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 285d801f-b49d-47ee-8745-61c02f41ea75
📒 Files selected for processing (3)
src/datamodel_code_generator/__main__.pysrc/datamodel_code_generator/reference.pysrc/datamodel_code_generator/types.py
Breaking Change AnalysisResult: Breaking changes detected Reasoning: This PR removes the Pydantic v1 runtime compatibility layer entirely. Key changes include: (1) Removal of Content for Release NotesDependency Changes
This analysis was performed by Claude Code Action |
|
🎉 Released in 0.55.0 This PR is now available in the latest release. See the release notes for details. |
Summary by CodeRabbit
Breaking Changes
Improvements
Tests / CI