Visitar URL original
Deduplicate DataType type hint rendering by koxudaxi · Pull Request #3354 · datamodel-code-generator/datamodel-code-generator · GitHub
Skip to content

Deduplicate DataType type hint rendering - #3354

Merged
Koudai Aono (koxudaxi) merged 4 commits into
mainfrom
refactor/datatype-type-hint-core
Jun 12, 2026
Merged

Koudai Aono (koxudaxi) merged 4 commits into
mainfrom
refactor/datatype-type-hint-core

Conversation

@koxudaxi

@koxudaxi Koudai Aono (koxudaxi) commented Jun 12, 2026 •

Copy link
Copy Markdown
Member

No description provided.

@coderabbitai

coderabbitai Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a72b07b7-f833-435b-aab3-8259709800a5

📥 Commits

Reviewing files that changed from the base of the PR and between a3b3016 and 8f1750f.

📒 Files selected for processing (2)
  • tests/main/jsonschema/test_main_jsonschema.py
  • tests/parser/test_jsonschema.py

📝 Walkthrough

Walkthrough

This PR refactors DataType.type_hint and DataType.base_type_hint by extracting nested-type rendering into helper methods, introducing container-order class constants, and delegating container wrapping to a configurable phase. Tests were added for rendering precedence, dict-key rendering, union ordering, mutation carryover, and optional-wrapping placement.

Changes

Type-hint rendering refactoring

Layer / File(s) Summary
Helper methods and container-order constants
src/datamodel_code_generator/types.py
Added _TYPE_HINT_CONTAINER_ORDER and _BASE_TYPE_HINT_CONTAINER_ORDER class constants and helper methods to render nested types (union/tuple/literal/reference handling, None removal, discriminator wrapping) and to apply container wrapping in a specific order.
base_type_hint property rework
src/datamodel_code_generator/types.py
Adjusted base_type_hint signature formatting and reimplemented its nested-type rendering to call the shared helper with wrap_discriminator=False, then apply nullable propagation and wrap containers using _BASE_TYPE_HINT_CONTAINER_ORDER (list/set/dict).
type_hint composition
src/datamodel_code_generator/types.py
Replaced inline branching in type_hint with helper-driven composition: use nested-render helper, propagate Nullable-based nullability, then apply container wrapping via _TYPE_HINT_CONTAINER_ORDER.
Test import adjustments
tests/test_types.py
Added TYPE_CHECKING import and a TYPE_CHECKING guard to import Callable from collections.abc only for typing.
Test assertions for type-hint behavior
tests/test_types.py
Added multiple new tests covering container precedence asymmetry, dict key rendering for constrained keys, bare Dict rendering, no-container fallback, base_type_hint nullability propagation from Reference, union order preservation, repeated-property mutation carryover, and optional wrapping order for constrained function types.

🎯 4 (Complex) | ⏱️ ~45 minutes

  • Possibly related PRs:

  • Suggested labels:
    breaking-change-analyzed

"🐰 I hop through hints and wraps with cheer,
Nested types aligned, no None to fear,
Containers wrapped in ordered dress,
Tests guard order, keys, and optionalness,
A little carrot of code — refined and clear!"

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title 'Deduplicate DataType type hint rendering' directly corresponds to the main refactoring objective described in the raw summary: extracting inline branching logic into reusable helper methods to eliminate code duplication in type hint generation.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/datatype-type-hint-core

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

github-actions Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

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

@codspeed

codspeed Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

⚠️ 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.

✅ 11 untouched benchmarks
⏩ 98 skipped benchmarks1


Comparing refactor/datatype-type-hint-core (8f1750f) with main (276caac)

Open in CodSpeed

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. ↩

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/datamodel_code_generator/types.py`:
- Around line 838-853: The union member handling currently appends
raw/non-normalized members to data_types then normalizes None-containing
members, which can produce duplicate entries (e.g., Union[int, int]); update the
logic around data_type_type, _remove_none_from_union, and data_types so you
normalize each member first (use non_optional_data_type_type =
_remove_none_from_union(...)), set self.is_optional if normalization changed it
or if data_type_type == NONE, then only append non_optional_data_type_type to
data_types if it's truthy and not already present (avoid adding duplicates when
multiple originals normalize to the same type); keep references to NONE,
_remove_none_from_union, self.is_optional, self.use_union_operator, and
data_types to locate and modify this block.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 43d073e7-fad4-4eb2-999d-a68d70a705cb

📥 Commits

Reviewing files that changed from the base of the PR and between 276caac and 4771970.

📒 Files selected for processing (2)
  • src/datamodel_code_generator/types.py
  • tests/test_types.py

Comment thread src/datamodel_code_generator/types.py
@koxudaxi
Koudai Aono (koxudaxi) force-pushed the refactor/datatype-type-hint-core branch from 4771970 to 4ec51c3 Compare June 12, 2026 12:16
@codecov

codecov Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (276caac) to head (8f1750f).

Additional details and impacted files
@@             Coverage Diff             @@
##             main     #3354      +/-   ##
===========================================
+ Coverage   99.97%   100.00%   +0.02%     
===========================================
  Files         129       129              
  Lines       28468     28547      +79     
  Branches     3443      3448       +5     
===========================================
+ Hits        28460     28547      +87     
+ Misses          5         0       -5     
+ Partials        3         0       -3     
Flag Coverage Δ
unittests 100.00% <100.00%> (+0.02%) ⬆️

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

☔ View full report in Codecov by Harness.
📢 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
Koudai Aono (koxudaxi) merged commit cebebff into main Jun 12, 2026
52 checks passed
@koxudaxi
Koudai Aono (koxudaxi) deleted the refactor/datatype-type-hint-core branch June 12, 2026 13:15
@github-actions

Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: PR #3354 "Deduplicate DataType type hint rendering" is an internal, behavior-preserving refactor. The merged source (src/datamodel_code_generator/types.py) shows DataType.type_hint and DataType.base_type_hint now share newly extracted PRIVATE helper methods (_wrap_container_type_hint, _container_type_hint_renderer, wrap*_type_hint, _TYPE_HINT_CONTAINER_ORDER) instead of duplicating container-wrapping logic. The public properties type_hint and base_type_hint retain identical names/signatures. The PR's own commits add characterization tests and edge-case/JSON-schema-import tests, whose purpose is to lock the existing generated output so the deduplication yields identical results — indicating no change to generated code. No CLI options, Python API surface, default values/behavior, Jinja2 templates, Python version support, or error handling are altered. Note: the prepared diff files under /home/runner/work/_temp/ were unreadable in this sandbox (blocked across Read, Bash, subagent, and gh) and the repo is a shallow single-commit clone, so this determination is grounded in the merged commit metadata and the merged source code of the changed area rather than the prepared diff.


This analysis was performed by Claude Code Action

@github-actions

Copy link
Copy Markdown
Contributor

🎉 Released in 0.64.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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant