Skip to content

Conversation

@phil65
Copy link

@phil65 phil65 commented Jan 7, 2026

… access

The UnionMode type is used in GenerateConfig.union_mode field annotation. Pydantic needs to access this type at runtime for model validation, but it was only imported inside TYPE_CHECKING block, causing:

PydanticUserError: GenerateConfig is not fully defined; you should define UnionMode, then call GenerateConfig.model_rebuild().

This follows the same pattern as other runtime-required imports in this file (Path, DataModel, DataModelFieldBase, etc.) which have noqa: TC001 comments.

Summary by CodeRabbit

  • Refactor
    • A previously internal type is now publicly available for import from the library.

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

… access

The UnionMode type is used in GenerateConfig.union_mode field annotation.
Pydantic needs to access this type at runtime for model validation, but it
was only imported inside TYPE_CHECKING block, causing:

PydanticUserError: GenerateConfig is not fully defined; you should define
UnionMode, then call GenerateConfig.model_rebuild().

This follows the same pattern as other runtime-required imports in this file
(Path, DataModel, DataModelFieldBase, etc.) which have noqa: TC001 comments.
Copilot AI review requested due to automatic review settings January 7, 2026 03:29
@coderabbitai
Copy link

coderabbitai bot commented Jan 7, 2026

📝 Walkthrough

Walkthrough

UnionMode is now imported at module scope from datamodel_code_generator.model.pydantic_v2 in src/datamodel_code_generator/config.py, replacing a TYPE_CHECKING-guarded import. This makes UnionMode directly importable at runtime for both typing and runtime usage.

Changes

Cohort / File(s) Summary
Import Structure Changes
src/datamodel_code_generator/config.py
Moved UnionMode import from TYPE_CHECKING block to module-scope import, making it available for runtime usage and direct importation

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~2 minutes

Poem

🐰 A hop, a skip, an import so bright,
UnionMode now shines in runtime light!
No TYPE_CHECKING chains to bind,
Free at last—what peace to find!

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and accurately summarizes the main change: moving the UnionMode import outside the TYPE_CHECKING block for Pydantic runtime access.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings

📜 Recent 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 4decf36 and fa175a7.

📒 Files selected for processing (1)
  • src/datamodel_code_generator/config.py
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: koxudaxi
Repo: koxudaxi/datamodel-code-generator PR: 2799
File: src/datamodel_code_generator/model/pydantic/__init__.py:43-43
Timestamp: 2025-12-25T09:22:22.481Z
Learning: In datamodel-code-generator project, defensive `# noqa: PLC0415` directives should be kept on lazy imports (imports inside functions/methods) even when Ruff reports them as unused via RUF100, to prepare for potential future Ruff configuration changes that might enable the import-outside-top-level rule.
📚 Learning: 2025-12-25T09:23:08.506Z
Learnt from: koxudaxi
Repo: koxudaxi/datamodel-code-generator PR: 2799
File: src/datamodel_code_generator/util.py:49-66
Timestamp: 2025-12-25T09:23:08.506Z
Learning: In datamodel-code-generator, the is_pydantic_v2() and is_pydantic_v2_11() functions in src/datamodel_code_generator/util.py intentionally use global variable caching (_is_v2, _is_v2_11) on top of lru_cache for performance optimization. This dual-layer caching eliminates function call overhead and cache lookup overhead for frequently-called version checks. The PLW0603 linter warnings should be suppressed with # noqa: PLW0603 as this is a deliberate design choice.

Applied to files:

  • src/datamodel_code_generator/config.py
🧬 Code graph analysis (1)
src/datamodel_code_generator/config.py (1)
src/datamodel_code_generator/enums.py (1)
  • UnionMode (212-216)
🪛 Ruff (0.14.10)
src/datamodel_code_generator/config.py

47-47: Unused noqa directive (non-enabled: TC001)

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). (2)
  • GitHub Check: Agent
  • GitHub Check: CodeQL analysis (python)
🔇 Additional comments (2)
src/datamodel_code_generator/config.py (2)

47-47: Regarding the RUF100 static analysis hint: Keep the noqa directive.

Ruff reports the noqa: TC001 directive as unused, but this should be retained. The project follows a defensive pattern of keeping noqa directives even when not currently triggered, to prepare for potential future linter configuration changes. This aligns with existing runtime imports in this file (lines 7, 43, 51, 53) that all use the same noqa: TC001 pattern.

Based on learnings.


47-47: Import path is correct and follows project conventions.

The import of UnionMode from datamodel_code_generator.model.pydantic_v2 is correct. The pydantic_v2/__init__.py module explicitly re-exports UnionMode from datamodel_code_generator.enums, making this the intended public API import path. The noqa: TC001 directive is appropriate because it correctly suppresses the type-checking-only import check while documenting the runtime requirement for Pydantic validation.

The change properly moves UnionMode outside the TYPE_CHECKING block to fix the PydanticUserError, and the import path and suppression directive are correct.


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.

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes a Pydantic runtime validation error by moving the UnionMode import outside the TYPE_CHECKING block. The type annotation is used in the GenerateConfig.union_mode field and must be accessible at runtime for Pydantic model validation.

Key changes:

  • Moved UnionMode import from TYPE_CHECKING block to runtime imports
  • Added noqa: TC001 comment to suppress type-checking linter warning, consistent with other runtime-required imports

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@phil65
Copy link
Author

phil65 commented Jan 7, 2026

Alternatively this here in pyproject :)

[tool.ruff.lint.flake8-type-checking]
runtime-evaluated-base-classes = ["pydantic.BaseModel"]

@codspeed-hq
Copy link

codspeed-hq bot commented Jan 7, 2026

CodSpeed Performance Report

Merging this PR will degrade performance by 15.48%

Comparing phil65:fix/unionmode-type-checking-import (fa175a7) with main (4decf36)

⚠️ 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 regressed benchmarks
⏩ 98 skipped benchmarks1

⚠️ Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Mode Benchmark BASE HEAD Efficiency
WallTime test_perf_duplicate_names 842.7 ms 988.2 ms -14.73%
WallTime test_perf_deep_nested 5.2 s 5.9 s -12.83%
WallTime test_perf_kubernetes_style_pydantic_v2 2.2 s 2.6 s -15.32%
WallTime test_perf_aws_style_openapi_pydantic_v2 1.7 s 1.9 s -12.54%
WallTime test_perf_graphql_style_pydantic_v2 705 ms 809.8 ms -12.94%
WallTime test_perf_complex_refs 1.8 s 2 s -12.07%
WallTime test_perf_multiple_files_input 3.2 s 3.8 s -15.48%
WallTime test_perf_stripe_style_pydantic_v2 1.7 s 1.9 s -14%
WallTime test_perf_all_options_enabled 5.8 s 6.7 s -13.55%
WallTime test_perf_openapi_large 2.5 s 2.9 s -14.3%
WallTime test_perf_large_models_pydantic_v2 3.1 s 3.6 s -15.14%

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.

@codecov
Copy link

codecov bot commented Jan 7, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (4decf36) to head (fa175a7).

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #2950   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           94        94           
  Lines        17716     17717    +1     
  Branches      2037      2037           
=========================================
+ Hits         17716     17717    +1     
Flag Coverage Δ
unittests 100.00% <100.00%> (ø)

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.

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