Skip to content

Add faux immutability option#569

Merged
koxudaxi merged 1 commit intomainfrom
issue-441-hashable-models
Apr 28, 2026
Merged

Add faux immutability option#569
koxudaxi merged 1 commit intomainfrom
issue-441-hashable-models

Conversation

@koxudaxi
Copy link
Copy Markdown
Owner

@koxudaxi koxudaxi commented Apr 28, 2026

Fixes: #441

Summary

  • Add --enable-faux-immutability and pass it through to datamodel-code-generator.
  • Allow generated Pydantic models to use ConfigDict(frozen=True), making instances hashable when their fields are hashable.
  • Update generated CLI/config documentation and add regression coverage for hashable enum-backed request models.

Tests

  • uv run pytest -q
  • uv run pytest --collect-cli-docs tests/main/test_main.py tests/cli_doc -q
  • uv run python scripts/build_cli_docs.py --check
  • uv run python scripts/build_prompt_data.py --output fastapi_code_generator/prompt_data.py --check
  • uv run python scripts/build_schema_docs.py --check
  • uv run python scripts/build_config_types.py --check
  • uv run python scripts/update_command_help_on_markdown.py --check
  • uv run python scripts/build_llms_txt.py --check

Summary by CodeRabbit

  • New Features

    • Added a --enable-faux-immutability CLI option to generate frozen Pydantic models so instances are hashable when their fields are hashable.
  • Documentation

    • Updated CLI reference, help snapshots, examples, and fixture inventories to document the new option and show an example invocation.
  • Tests

    • Added tests and golden output to exercise the new option and confirm generated models support hashing.
  • Examples

    • Added a coverage example and generated sample outputs demonstrating faux immutability.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 28, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2b8a1618-add4-47bf-bc15-88e5ddd2f1c2

📥 Commits

Reviewing files that changed from the base of the PR and between 69a44cf and 7654ba8.

📒 Files selected for processing (13)
  • README.md
  • docs/cli-reference.md
  • docs/index.md
  • docs/llms-full.txt
  • docs/supported_formats.md
  • fastapi_code_generator/_types/generate_config_dict.py
  • fastapi_code_generator/cli.py
  • fastapi_code_generator/config.py
  • fastapi_code_generator/prompt_data.py
  • tests/data/expected/openapi/coverage/faux_immutability/main.py
  • tests/data/expected/openapi/coverage/faux_immutability/models.py
  • tests/data/openapi/coverage/faux_immutability.yaml
  • tests/main/test_main.py
✅ Files skipped from review due to trivial changes (5)
  • README.md
  • docs/index.md
  • docs/supported_formats.md
  • fastapi_code_generator/_types/generate_config_dict.py
  • docs/cli-reference.md
🚧 Files skipped from review as they are similar to previous changes (5)
  • tests/data/expected/openapi/coverage/faux_immutability/models.py
  • fastapi_code_generator/cli.py
  • fastapi_code_generator/prompt_data.py
  • tests/data/expected/openapi/coverage/faux_immutability/main.py
  • docs/llms-full.txt

Walkthrough

Adds a new CLI flag --enable-faux-immutability that, when passed, instructs the generator to produce frozen Pydantic models (hashable when their fields are hashable). The flag is propagated through CLI, config types, prompt metadata, parser invocation, docs, fixtures, and tests validating hashability.

Changes

Cohort / File(s) Summary
Documentation
README.md, docs/cli-reference.md, docs/index.md, docs/llms-full.txt, docs/supported_formats.md
Documented new --enable-faux-immutability CLI flag, added example invocation and updated fixture inventory to include faux_immutability.yaml.
Config Types & Models
fastapi_code_generator/_types/generate_config_dict.py, fastapi_code_generator/config.py
Added enable_faux_immutability to GenerateConfigDict TypedDict and GenerateConfig (bool, default False) with CLI metadata.
CLI & Generator wiring
fastapi_code_generator/cli.py
Added --enable-faux-immutability CLI option and updated main()/generate_code() signatures to forward the flag into the parser/generation pipeline.
Prompt / Metadata
fastapi_code_generator/prompt_data.py
Registered enable_faux_immutability in PROMPT_DATA["config_options"], added CLI example using openapi/coverage/faux_immutability.yaml, and updated embedded schema/docs preview counts.
Tests & Fixtures
tests/main/test_main.py, tests/data/openapi/coverage/faux_immutability.yaml, tests/data/expected/openapi/coverage/faux_immutability/models.py, tests/data/expected/openapi/coverage/faux_immutability/main.py
Added OpenAPI fixture and expected outputs showing ConfigDict(frozen=True) on generated models; added tests that run the generator with the flag and assert instances (e.g., DraftRequest) are hashable.

Sequence Diagram(s)

sequenceDiagram
    participant User as "User (CLI)"
    participant CLI as "fastapi_code_generator.cli"
    participant Parser as "OpenAPIParser / Generator"
    participant FS as "Filesystem (templates/output)"
    User->>CLI: run generator with --enable-faux-immutability
    CLI->>Parser: generate_code(enable_faux_immutability=True)
    Parser->>Parser: select model templates with ConfigDict(frozen=True)
    Parser->>FS: write generated modules (models.py, main.py, ...)
    FS-->>User: generated files containing frozen models
    Note over Parser,FS: tests load generated models and assert hash(instance) is int
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 A tiny flag hops into view so bright,
Frozen models now hold fast and tight.
Drafts can be hashed with a joyful cheer,
I nibble the docs and give one happy ear. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.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 title 'Add faux immutability option' is concise and accurately reflects the main change—introducing a new --enable-faux-immutability CLI flag and configuration option that enables frozen Pydantic models for hashability.
Linked Issues check ✅ Passed The PR fully addresses issue #441 by implementing the --enable-faux-immutability option that allows generated Pydantic models to use ConfigDict(frozen=True), making instances hashable when their fields are hashable.
Out of Scope Changes check ✅ Passed All changes are directly related to the linked issue #441: CLI option addition, config handling, documentation updates, test coverage, and an OpenAPI fixture for the faux immutability feature. No unrelated modifications detected.

✏️ 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 issue-441-hashable-models

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

github-actions Bot commented Apr 28, 2026

📚 Docs Preview: https://pr-569.fastapi-code-generator.pages.dev

@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented Apr 28, 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.

✅ 1 untouched benchmark


Comparing issue-441-hashable-models (7654ba8) with main (23a9e75)

Open in CodSpeed

@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 28, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (23a9e75) to head (7654ba8).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main      #569   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           17        17           
  Lines         1271      1285   +14     
  Branches       131       131           
=========================================
+ Hits          1271      1285   +14     
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.

@koxudaxi koxudaxi marked this pull request as ready for review April 28, 2026 05:04
@koxudaxi koxudaxi force-pushed the issue-441-hashable-models branch from a84256d to 382021d Compare April 28, 2026 05:07
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

🧹 Nitpick comments (1)
fastapi_code_generator/prompt_data.py (1)

356-360: Align example wording with the CLI hashability caveat.

The scenario description is slightly more absolute than the help text. Consider reusing the same “when fields are hashable” phrasing for consistency across generated docs.

✏️ Suggested wording tweak
-            'description': 'Generate frozen Pydantic models for hashable model '
-            'instances.',
+            'description': 'Generate frozen Pydantic models so instances are '
+            'hashable when their fields are hashable.',
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@fastapi_code_generator/prompt_data.py` around lines 356 - 360, Update the
'description' string in the option dict (the entry with 'options':
['--enable-faux-immutability']) to mirror the CLI caveat wording by replacing
the current absolute phrasing with the conditional phrasing "when fields are
hashable" (e.g., "Generate frozen Pydantic models when fields are hashable.") so
the prompt example and CLI help are consistent.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@tests/main/test_main.py`:
- Line 787: The use of exec(models, namespace) triggers Ruff S102; add an inline
suppression and rationale directly on that line to acknowledge intentional use
of exec in the test (e.g., append a noqa comment like "# noqa: S102 -- executing
generated test models in a controlled test namespace" or similar), so the linter
is waived but the reason is recorded; ensure the comment references exec(models,
namespace) and explains that execution is limited to the test-controlled
namespace.

---

Nitpick comments:
In `@fastapi_code_generator/prompt_data.py`:
- Around line 356-360: Update the 'description' string in the option dict (the
entry with 'options': ['--enable-faux-immutability']) to mirror the CLI caveat
wording by replacing the current absolute phrasing with the conditional phrasing
"when fields are hashable" (e.g., "Generate frozen Pydantic models when fields
are hashable.") so the prompt example and CLI help are consistent.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1a2b2f3d-e53d-4942-834e-8ecef104873d

📥 Commits

Reviewing files that changed from the base of the PR and between e9f2965 and a84256d.

📒 Files selected for processing (9)
  • README.md
  • docs/cli-reference.md
  • docs/index.md
  • docs/llms-full.txt
  • fastapi_code_generator/_types/generate_config_dict.py
  • fastapi_code_generator/cli.py
  • fastapi_code_generator/config.py
  • fastapi_code_generator/prompt_data.py
  • tests/main/test_main.py

Comment thread tests/main/test_main.py Outdated
@koxudaxi koxudaxi force-pushed the issue-441-hashable-models branch from 382021d to 69a44cf Compare April 28, 2026 05:09
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.

♻️ Duplicate comments (1)
tests/main/test_main.py (1)

38-38: ⚠️ Potential issue | 🟠 Major

Add intentional Ruff waiver for exec on Line 38.

exec is test-intentional here, but without an inline waiver this can fail lint (S102).

🔧 Minimal fix
-    exec(models_path.read_text(encoding="utf-8"), namespace)
+    exec(  # noqa: S102 - executing generated fixture code in test-controlled namespace
+        models_path.read_text(encoding="utf-8"), namespace
+    )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/main/test_main.py` at line 38, Add an inline Ruff waiver for the
intentional exec usage on the exec(models_path.read_text(encoding="utf-8"),
namespace) line so the S102 lint rule is ignored; locate that exact exec call in
tests/main/test_main.py and append an inline ruff/NOQA waiver for S102 (e.g.,
use the ruff-specific noqa for rule S102) to suppress the lint error while
keeping the intent clear.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@tests/main/test_main.py`:
- Line 38: Add an inline Ruff waiver for the intentional exec usage on the
exec(models_path.read_text(encoding="utf-8"), namespace) line so the S102 lint
rule is ignored; locate that exact exec call in tests/main/test_main.py and
append an inline ruff/NOQA waiver for S102 (e.g., use the ruff-specific noqa for
rule S102) to suppress the lint error while keeping the intent clear.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 724271ba-4823-41c9-b0f2-5cce89856c33

📥 Commits

Reviewing files that changed from the base of the PR and between a84256d and 382021d.

📒 Files selected for processing (13)
  • README.md
  • docs/cli-reference.md
  • docs/index.md
  • docs/llms-full.txt
  • docs/supported_formats.md
  • fastapi_code_generator/_types/generate_config_dict.py
  • fastapi_code_generator/cli.py
  • fastapi_code_generator/config.py
  • fastapi_code_generator/prompt_data.py
  • tests/data/expected/openapi/coverage/faux_immutability/main.py
  • tests/data/expected/openapi/coverage/faux_immutability/models.py
  • tests/data/openapi/coverage/faux_immutability.yaml
  • tests/main/test_main.py
✅ Files skipped from review due to trivial changes (7)
  • fastapi_code_generator/_types/generate_config_dict.py
  • docs/cli-reference.md
  • docs/index.md
  • tests/data/expected/openapi/coverage/faux_immutability/main.py
  • README.md
  • tests/data/expected/openapi/coverage/faux_immutability/models.py
  • docs/supported_formats.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • fastapi_code_generator/config.py

@koxudaxi koxudaxi force-pushed the issue-441-hashable-models branch from 69a44cf to 7654ba8 Compare April 28, 2026 05:12
@koxudaxi koxudaxi merged commit 7f653a0 into main Apr 28, 2026
45 checks passed
@koxudaxi koxudaxi deleted the issue-441-hashable-models branch April 28, 2026 06:02
@github-actions github-actions Bot added the breaking-change-analyzed PR has been checked for release draft updates label Apr 28, 2026
@github-actions
Copy link
Copy Markdown
Contributor

Breaking Change Analysis

Result: No breaking changes detected

Reasoning: The breaking-change label is absent, so this PR is treated as a non-breaking release update.


This analysis was performed by repository automation using PR labels and the ## Breaking Changes section.

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

Labels

breaking-change-analyzed PR has been checked for release draft updates

Projects

None yet

Development

Successfully merging this pull request may close these issues.

FastAPI code generator generating unhashable models when using an enum

1 participant