Skip to content

Refactor: Use model_validate/parse_obj for Parser config initialization#2880

Merged
koxudaxi merged 1 commit intomainfrom
refactor/parser-config-model-validate
Dec 31, 2025
Merged

Refactor: Use model_validate/parse_obj for Parser config initialization#2880
koxudaxi merged 1 commit intomainfrom
refactor/parser-config-model-validate

Conversation

@koxudaxi
Copy link
Copy Markdown
Owner

@koxudaxi koxudaxi commented Dec 31, 2025

Summary by CodeRabbit

  • Refactor
    • Internal improvements to code structure and maintainability with no user-visible behavior changes.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Dec 31, 2025

📝 Walkthrough

Walkthrough

The PR refactors the generate() function to extract parser configuration creation into a new internal helper _create_parser_config, which merges base GenerateConfig with parser-specific options while handling Pydantic v1/v2 compatibility. Parser instantiation is reorganized to use this centralized configuration builder across all input types.

Changes

Cohort / File(s) Change Summary
Parser Configuration Refactoring
src/datamodel_code_generator/__init__.py
Introduces new _create_parser_config() helper for building parser config with Pydantic v1/v2 compatibility (model_validate/model_copy vs. parse_obj); adds _ConfigT TypeVar and updates TYPE_CHECKING imports for parser config types (GraphQLParserConfigDict, OpenAPIParserConfigDict, ParserConfigDict); refactors generate() to use this helper for all parser types; reorganizes RAW_DATA_TYPES handling with explicit paths for CSV, YAML, JSON, Dict inputs; adds logic to compute default parser configuration fields (target_datetime_class, enum_field_as_literal, set_default_enum_member).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • PR #2874: Both PRs modify the generate() implementation to refactor parser configuration creation and instantiation, with one changing generate() signature to config-driven form.
  • PR #2878: Both PRs centralize parser configuration creation and pass configuration objects to parsers instead of multiple keyword arguments.

Poem

🐰 A parser's tale, now neatly told,
With configs merged, no more to fold,
From OpenAPI to GraphQL's call,
One helper function rules them all!
Compatibility secured, the path is clear,
Configuration generation draws near!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main refactoring change: replacing parser instantiation patterns with model_validate/parse_obj for configuration initialization, which is the primary objective of the pull request.
✨ Finishing touches
  • 📝 Generate docstrings

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions
Copy link
Copy Markdown
Contributor

📚 Docs Preview: https://pr-2880.datamodel-code-generator.pages.dev

@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented Dec 31, 2025

CodSpeed Performance Report

Merging #2880 will not alter performance

Comparing refactor/parser-config-model-validate (d760dfd) with main (efe8dfa)

⚠️ Unknown Walltime execution environment detected

Using the Walltime instrument on standard Hosted Runners will lead to inconsistent data.

For the most accurate results, we recommend using CodSpeed Macro Runners: bare-metal machines fine-tuned for performance measurement consistency.

Summary

✅ 11 untouched
⏩ 98 skipped1

Footnotes

  1. 98 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/datamodel_code_generator/__init__.py (1)

605-660: Consider removing unused noqa directives.

Static analysis indicates that several # noqa: PLC0415 directives in this block (lines 606, 614, 625, 641, 656) are unused because the PLC0415 rule is not enabled. If the rule is intentionally disabled project-wide, these directives can be safely removed to reduce noise.

🔎 Proposed cleanup
-        import json  # noqa: PLC0415
+        import json

             import csv  # noqa: PLC0415
-            import csv  # noqa: PLC0415
+            import csv

-                    import io  # noqa: PLC0415
+                    import io

-                import ast  # noqa: PLC0415
+                import ast

-        from genson import SchemaBuilder  # noqa: PLC0415
+        from genson import SchemaBuilder
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between efe8dfa and d760dfd.

📒 Files selected for processing (1)
  • src/datamodel_code_generator/__init__.py
🧰 Additional context used
🧬 Code graph analysis (1)
src/datamodel_code_generator/__init__.py (9)
src/datamodel_code_generator/_types/graphql_parser_config_dict.py (1)
  • GraphQLParserConfigDict (33-146)
src/datamodel_code_generator/_types/openapi_parser_config_dict.py (1)
  • OpenAPIParserConfigDict (34-148)
src/datamodel_code_generator/_types/parser_config_dict.py (1)
  • ParserConfigDict (33-144)
src/datamodel_code_generator/_types/generate_config_dict.py (1)
  • GenerateConfigDict (39-160)
src/datamodel_code_generator/config.py (5)
  • GenerateConfig (65-198)
  • ParserConfig (201-324)
  • GraphQLParserConfig (327-331)
  • JSONSchemaParserConfig (334-335)
  • OpenAPIParserConfig (338-343)
src/datamodel_code_generator/util.py (2)
  • is_pydantic_v2 (52-57)
  • model_validate (261-265)
src/datamodel_code_generator/parser/jsonschema.py (2)
  • parse_obj (3450-3495)
  • JsonSchemaParser (526-3646)
src/datamodel_code_generator/parser/openapi.py (1)
  • OpenAPIParser (164-767)
src/datamodel_code_generator/parser/graphql.py (1)
  • GraphQLParser (62-508)
🪛 Ruff (0.14.10)
src/datamodel_code_generator/__init__.py

606-606: Unused noqa directive (non-enabled: PLC0415)

Remove unused noqa directive

(RUF100)


614-614: Unused noqa directive (non-enabled: PLC0415)

Remove unused noqa directive

(RUF100)


625-625: Unused noqa directive (non-enabled: PLC0415)

Remove unused noqa directive

(RUF100)


641-641: Unused noqa directive (non-enabled: PLC0415)

Remove unused noqa directive

(RUF100)


656-656: Unused noqa directive (non-enabled: PLC0415)

Remove unused noqa directive

(RUF100)


691-691: Unused noqa directive (non-enabled: PLC0415)

Remove unused noqa directive

(RUF100)


731-731: Unused noqa directive (non-enabled: PLC0415)

Remove unused noqa directive

(RUF100)


742-742: Unused noqa directive (non-enabled: PLC0415)

Remove unused noqa directive

(RUF100)


752-752: Unused noqa directive (non-enabled: PLC0415)

Remove unused noqa directive

(RUF100)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (14)
  • GitHub Check: py312-isort7 on Ubuntu
  • GitHub Check: py312-isort5 on Ubuntu
  • GitHub Check: py312-black22 on Ubuntu
  • GitHub Check: 3.12 on Windows
  • GitHub Check: 3.10 on Ubuntu
  • GitHub Check: 3.10 on macOS
  • GitHub Check: 3.11 on Windows
  • GitHub Check: py312-isort6 on Ubuntu
  • GitHub Check: 3.10 on Windows
  • GitHub Check: 3.12 on Ubuntu
  • GitHub Check: 3.14 on Windows
  • GitHub Check: 3.13 on Windows
  • GitHub Check: benchmarks
  • GitHub Check: Analyze (python)
🔇 Additional comments (5)
src/datamodel_code_generator/__init__.py (5)

64-72: LGTM!

The new TYPE_CHECKING imports and the _ConfigT TypeVar bound to ParserConfig are correctly defined for supporting the generic _create_parser_config helper.


697-728: LGTM!

The additional_options dictionary correctly computes conditional defaults for target_datetime_class, enum_field_as_literal, and set_default_enum_member based on the input file type and output model type.


730-755: LGTM!

The parser instantiation is cleanly refactored to use _create_parser_config for all three parser types (OpenAPI, GraphQL, JSONSchema). The pattern of merging common additional_options with parser-specific options via spread operator is appropriate.


691-695: LGTM!

The parser config class imports are correctly placed at the point of use within the generate() function.


452-470: No issues found. The extra="ignore" parameter is a valid argument to model_validate() in Pydantic v2. According to the official Pydantic v2 documentation, model_validate() accepts the extra parameter, which controls how extra fields are handled during validation (allow/ignore/forbid) and overrides the model-level configuration for that validation call.

@codecov
Copy link
Copy Markdown

codecov Bot commented Dec 31, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.38%. Comparing base (efe8dfa) to head (d760dfd).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2880   +/-   ##
=======================================
  Coverage   99.38%   99.38%           
=======================================
  Files          91       91           
  Lines       15643    15649    +6     
  Branches     1848     1848           
=======================================
+ Hits        15547    15553    +6     
  Misses         50       50           
  Partials       46       46           
Flag Coverage Δ
unittests 99.38% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@koxudaxi koxudaxi merged commit 36530b1 into main Dec 31, 2025
37 checks passed
@koxudaxi koxudaxi deleted the refactor/parser-config-model-validate branch December 31, 2025 04:40
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Jan 1, 2026

🎉 Released in 0.51.0

This PR is now available in the latest release. See the release notes for details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant