Skip to content

Skip default_factory wrapping for non-callable type aliases#3012

Merged
koxudaxi merged 4 commits intokoxudaxi:mainfrom
butvinm:fix/type-alias-default-factory-3009
Mar 3, 2026
Merged

Skip default_factory wrapping for non-callable type aliases#3012
koxudaxi merged 4 commits intokoxudaxi:mainfrom
butvinm:fix/type-alias-default-factory-3009

Conversation

@butvinm
Copy link
Copy Markdown
Contributor

@butvinm butvinm commented Mar 2, 2026

Fix #3009

Summary by CodeRabbit

  • Bug Fixes

    • Prevented unnecessary wrapping of root-model default values when the root reference is a type alias.
  • Tests

    • Added tests covering enum-literal type alias defaults with combined configuration flags to ensure defaults are not wrapped.

…udaxi#3009)

When --use-type-alias + --use-annotated + --enum-field-as-literal all are
combined, the generator produced `default_factory=lambda: Mode('default')`
where Mode is a PEP 695 type alias (not callable). Add a TypeAliasBase
guard in __wrap_root_model_default_values to skip wrapping for type aliases.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 2, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3371925 and 6e6d034.

📒 Files selected for processing (2)
  • src/datamodel_code_generator/parser/base.py
  • tests/main/jsonschema/test_main_jsonschema.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/datamodel_code_generator/parser/base.py

📝 Walkthrough

Walkthrough

Refines the guard that wraps root-model default values: wrapping now occurs only when data_type.reference.source is the root data model type and that source is not a TypeAliasBase, preventing defaults from being wrapped when the root reference is a type alias. No other control flow changes.

Changes

Cohort / File(s) Summary
Core Logic Guard
src/datamodel_code_generator/parser/base.py
Tightened the condition that wraps root-model default values by excluding cases where the root reference source is a TypeAliasBase, preventing generation of callables for type-alias defaults.
Generated Expected Output
tests/data/expected/main/jsonschema/enum_literal_type_alias_default.py
Added expected output showing a Mode = Literal['default','plan'] type alias and a Model with `mode: Mode
Test Case
tests/main/jsonschema/test_main_jsonschema.py
Added test test_main_jsonschema_enum_literal_type_alias_default (appears twice in this diff) to verify combined flags --use-type-alias, --use-annotated, --enum-field-as-literal all produce unwrapped defaults for type-alias roots targeting Python 3.12 / pydantic_v2.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

Suggested labels

breaking-change-analyzed

Poem

🐰 I hopped through parser lines with glee,
I nudged the guard so defaults stay free.
No calling aliases — a kinder fate,
Strings remain simple, tidy, and straight. ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly describes the main code change: narrowing the wrapping condition to skip default_factory wrapping for non-callable type aliases, which is the core fix for the linked issue.
Linked Issues check ✅ Passed The PR fixes issue #3009 by preventing default_factory wrapping for type aliases, which eliminates the invalid callable invocation of TypeAliasType in the generated code.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing the type alias default wrapping issue: the parser logic fix, the expected output test file, and the new test case all address the bug described in #3009.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

@butvinm butvinm marked this pull request as draft March 2, 2026 00:48
@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented Mar 2, 2026

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 butvinm:fix/type-alias-default-factory-3009 (dca857f) with main (c36ac6c)

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.

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: 1

🤖 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/parser/base.py`:
- Line 2161: The long conditional needs to be reformatted to satisfy
ruff-format: break the if condition into a parenthesized multi-line expression
and align each clause on its own line so the expression is wrapped and
PEP8-friendly (target the if in parser/base.py that references
data_type.reference, data_type.reference.source, self.data_model_root_type, and
TypeAliasBase); update the if at the start of the conditional to use parentheses
and line breaks for each isinstance check and the negation, then run the
project's formatter (ruff/black) to commit the formatted change so CI passes.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9955314 and 3371925.

⛔ Files ignored due to path filters (1)
  • tests/data/jsonschema/enum_literal_type_alias_default.json is excluded by !tests/data/**/*.json and included by none
📒 Files selected for processing (3)
  • src/datamodel_code_generator/parser/base.py
  • tests/data/expected/main/jsonschema/enum_literal_type_alias_default.py
  • tests/main/jsonschema/test_main_jsonschema.py

Comment thread src/datamodel_code_generator/parser/base.py Outdated
Skip the enum_literal_type_alias_default test on black < 23 since
PEP 695 `type` statement syntax is unsupported. Reformat long
conditional in parser/base.py to satisfy ruff line-length.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@codecov
Copy link
Copy Markdown

codecov Bot commented Mar 2, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (c36ac6c) to head (dca857f).
⚠️ Report is 4 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #3012   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           94        94           
  Lines        18130     18133    +3     
  Branches      2099      2099           
=========================================
+ Hits         18130     18133    +3     
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.

@butvinm butvinm marked this pull request as ready for review March 2, 2026 01:46
@butvinm
Copy link
Copy Markdown
Contributor Author

butvinm commented Mar 2, 2026

I am not sure how my code might cause performance regression. According to CodSpeed report, the regression seems to be coming from black formatting

@koxudaxi koxudaxi merged commit 69eda18 into koxudaxi:main Mar 3, 2026
39 checks passed
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Mar 3, 2026

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: This PR is a bug fix, not a breaking change. The previous behavior generated invalid Python code (wrapping type alias defaults in default_factory with a lambda that tries to call the type alias, which is not callable). The fix produces correct code. Breaking changes involve changing behavior that previously worked correctly - this PR corrects behavior that was always broken, making it a pure bug fix.


This analysis was performed by Claude Code Action

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Mar 4, 2026

🎉 Released in 0.54.1

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.

--use-type-alias + --use-annotated + --enum-field-as-literal all generates callable TypeAliasType in default_factory

2 participants