Skip to content

Add flag --use-default-keep-required-non-nullable#3086

Draft
GuillaumeSmaha wants to merge 8 commits intokoxudaxi:mainfrom
GuillaumeSmaha:add-default-on-required
Draft

Add flag --use-default-keep-required-non-nullable#3086
GuillaumeSmaha wants to merge 8 commits intokoxudaxi:mainfrom
GuillaumeSmaha:add-default-on-required

Conversation

@GuillaumeSmaha
Copy link
Copy Markdown

@GuillaumeSmaha GuillaumeSmaha commented Apr 14, 2026

Hi!

The aim is to provide a way to keep the field non nullable/optional when --use-default is used

    Pet:
      required:
        - id
        - name
      properties:
        id:
          type: integer
          format: int64
          default: 1
        name:
          type: string
        tag:
          type: string

wil become:

class Pet(BaseModel):
    id: int = 1
    name: str
    tag: str | None = None

instead of (current implementation):

class Pet(BaseModel):
    id: int | None = 1
    name: str
    tag: str | None = None

Summary by CodeRabbit

  • New Features

    • Added --use-default-keep-required-non-nullable CLI option: when used with --use-default, required fields remain non-nullable/non-optional instead of becoming nullable.
  • Documentation

    • Updated CLI reference and quick-reference with the new option and expanded examples showing OpenAPI input plus Pydantic v2, dataclass, msgspec, and JSON Schema output tabs.
  • Tests

    • Added CLI and generation tests and new expected model fixtures covering the new behavior.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 14, 2026

📝 Walkthrough

Walkthrough

This PR adds a new CLI option --use-default-keep-required-non-nullable and propagates it through CLI metadata, config models, parsers, and model emitters to prevent required fields from being downgraded to optional when defaults are applied.

Changes

Cohort / File(s) Summary
Documentation
docs/cli-reference/index.md, docs/cli-reference/model-customization.md, docs/cli-reference/quick-reference.md
Add new CLI option docs and examples; increment "Model Customization" option count and add links/anchoring for the new option.
CLI Arguments & Metadata
src/datamodel_code_generator/arguments.py, src/datamodel_code_generator/cli_options.py, src/datamodel_code_generator/prompt_data.py
Register new boolean CLI flag --use-default-keep-required-non-nullable, add CLI metadata entry and option description.
Top-level Config Wiring
src/datamodel_code_generator/__main__.py, src/datamodel_code_generator/_types/generate_config_dict.py, src/datamodel_code_generator/_types/parser_config_dicts.py, src/datamodel_code_generator/config.py
Add use_default_keep_required_non_nullable: bool to Config/TypedDicts and forward value into generate/run pipeline.
Parser Base & Instance State
src/datamodel_code_generator/parser/base.py, src/datamodel_code_generator/model/base.py
Expose the flag on parser and data-model-field base types; initialize instance attribute from config.
Parser Logic
src/datamodel_code_generator/parser/jsonschema.py, src/datamodel_code_generator/parser/openapi.py, src/datamodel_code_generator/parser/graphql.py
Guard logic that would convert required fields to optional when defaults exist so it only applies when the new flag is false.
Model Emitters
src/datamodel_code_generator/model/pydantic_base.py, src/datamodel_code_generator/model/dataclass.py, src/datamodel_code_generator/model/msgspec.py
Alter DataModelField.str and imports logic so required fields with defaults preserve default emission when the flag is enabled.
Tests & Fixtures
tests/main/openapi/test_main_openapi.py, tests/main/test_public_api_signature_baseline.py, tests/data/expected/.../*
Add CLI tests for the new flag, update baseline signatures and add expected output fixtures (pydantic/dataclass/msgspec) that reflect "keep required non-nullable" behavior.

Sequence Diagram(s)

sequenceDiagram
  participant CLI as CLI
  participant Config as Config
  participant Parser as Parser
  participant Generator as ModelGenerator
  participant Tests as Tests

  CLI->>Config: parse args (includes --use-default-keep-required-non-nullable)
  Config->>Parser: instantiate with flag
  Parser->>Parser: parse schemas (JSON Schema / OpenAPI / GraphQL)
  alt field has default and apply-default enabled
    Parser-->>Parser: if not use_default_keep_required_non_nullable -> mark field optional
    Parser-->>Parser: if use_default_keep_required_non_nullable -> keep required, retain default
  end
  Parser->>Generator: emit fields (pydantic/dataclass/msgspec) reflecting required/default semantics
  Generator->>Tests: generate output files compared against fixtures
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

safe-to-fix

Suggested reviewers

  • ilovelinux

Poem

🐇 I hop through flags and configs bright,
Keeping required fields firm and tight.
Defaults may bloom, but never make small —
Non-null they stand, proud and tall. ✨

🚥 Pre-merge checks | ✅ 3
✅ 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 'Add flag --use-default-keep-required-non-nullable' accurately describes the primary change: introducing a new CLI flag. It is concise, specific, and clearly identifies the main feature being added.
Docstring Coverage ✅ Passed Docstring coverage is 88.89% 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

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.

lambda key: self.model_resolver.get_valid_field_name_and_alias(
key, model_type=self.field_name_model_type
)[0]
self.get_field_extra_key: Callable[[str], str] = lambda key: (
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

uv run ruff format did this update

@GuillaumeSmaha GuillaumeSmaha marked this pull request as draft April 14, 2026 13:57
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: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/datamodel_code_generator/parser/jsonschema.py (1)

2845-2862: ⚠️ Potential issue | 🟠 Major

Preserve only default-induced nullability here.

keep_non_nullable is keyed only on required and effective_has_default, so this branch also forces nullable_override=False for fields that are already nullable in the schema (nullable: true / type contains null). That means enabling the new flag can silently remove a real None from the generated type instead of only undoing the optionality introduced by --use-default. Please gate this override on the field being non-nullable in the source schema.

Suggested fix
-            keep_non_nullable = self.use_default_keep_required_non_nullable and required and effective_has_default
+            keep_non_nullable = (
+                self.use_default_keep_required_non_nullable
+                and required
+                and effective_has_default
+                and field.nullable is not True
+                and not field.type_has_null
+            )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/datamodel_code_generator/parser/jsonschema.py` around lines 2845 - 2862,
The code currently sets nullable_override=False whenever keep_non_nullable is
true, but keep_non_nullable only checks required and effective_has_default and
can incorrectly clear schema-nullability; update the condition so
keep_non_nullable also verifies the source schema is non-nullable (e.g., the
schema's nullable flag or its type does not include "null") before flipping
required and before passing nullable_override=False into get_object_field; in
practice compute a boolean like source_is_non_nullable from the existing
field/schema metadata and change the logic that sets required and
nullable_override so nullable_override=False is only used when keep_non_nullable
and source_is_non_nullable are both true (leave nullable_override as None
otherwise).
🧹 Nitpick comments (4)
src/datamodel_code_generator/prompt_data.py (1)

123-123: Minor wording suggestion for clarity.

The description "keep required field non nullable/optional" is slightly ambiguous. The slash between "nullable" and "optional" might confuse users since these terms have different meanings. Consider rewording to clarify the intent:

  • Current: "When using default, keep required field non nullable/optional."
  • Suggested: "When using --use-default, keep required fields with defaults as non-nullable."

This is a minor documentation polish and doesn't affect functionality.

📝 Suggested wording improvement
-    "--use-default-keep-required-non-nullable": "When using default, keep required field non nullable/optional.",
+    "--use-default-keep-required-non-nullable": "When using --use-default, keep required fields with defaults as non-nullable.",
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/datamodel_code_generator/prompt_data.py` at line 123, Update the
description text for the CLI flag "--use-default-keep-required-non-nullable" in
prompt_data.py to be clearer: change the value from "When using default, keep
required field non nullable/optional." to something like "When using
--use-default, keep required fields with defaults as non-nullable." This targets
the string literal mapped to the key "--use-default-keep-required-non-nullable"
so the help/documentation reads unambiguously.
docs/cli-reference/quick-reference.md (1)

130-130: Minor grammar fix suggested by static analysis.

The term "non nullable" should be hyphenated as "non-nullable" when used as a compound adjective. This was flagged by LanguageTool.

📝 Hyphenation fix
-| [`--use-default-keep-required-non-nullable`](model-customization.md#use-default-keep-required-non-nullable) | When using default, keep required field non nullable/optional. |
+| [`--use-default-keep-required-non-nullable`](model-customization.md#use-default-keep-required-non-nullable) | When using default, keep required field non-nullable/optional. |

And for line 338:

-- [`--use-default-keep-required-non-nullable`](model-customization.md#use-default-keep-required-non-nullable) - When using default, keep required field non nullable/optiona...
+- [`--use-default-keep-required-non-nullable`](model-customization.md#use-default-keep-required-non-nullable) - When using default, keep required field non-nullable/optiona...

Also applies to: 338-338

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/cli-reference/quick-reference.md` at line 130, Replace the unhyphenated
phrase "non nullable" with the correct compound adjective "non-nullable" in the
documentation entries that mention the flag
`--use-default-keep-required-non-nullable` (the table row description) and the
other occurrence referenced in the comment; update both text occurrences so the
descriptions read "non-nullable/optional" (or similar) to fix the hyphenation.
src/datamodel_code_generator/arguments.py (1)

889-895: Clarify that this flag only takes effect with --use-default.

The current help text reads like a standalone toggle, but this option is really a modifier for --use-default. Making that dependency explicit in --help would avoid unnecessary confusion.

Suggested help text
 field_options.add_argument(
     "--use-default-keep-required-non-nullable",
-    help="When using default, keep required field non nullable/optional."
-    "E.g., `field: Model = Field(Model)` instead of `field: Model | None = Field(Model)`",
+    help="When used with --use-default, keep required fields non-nullable/non-optional. "
+    "E.g., `field: Model = Field(Model)` instead of `field: Model | None = Field(Model)`",
     action="store_true",
     default=None,
 )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/datamodel_code_generator/arguments.py` around lines 889 - 895, Update the
help text for the field_options.add_argument call that registers
"--use-default-keep-required-non-nullable" to explicitly state it only applies
when "--use-default" is used; change the help string in the
field_options.add_argument invocation (the
--use-default-keep-required-non-nullable argument) to mention it is a modifier
for --use-default and will have no effect unless --use-default is also provided.
src/datamodel_code_generator/__main__.py (1)

534-534: Consider warning when this flag is set without --use-default.

use_default_keep_required_non_nullable appears to be meaningful only with use_default; a small validation/warning would avoid silent no-op behavior.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/datamodel_code_generator/__main__.py` at line 534, Add a runtime check
after parsing flags to warn the user if use_default_keep_required_non_nullable
is True while use_default is False; specifically, in the main argument-handling
flow where use_default_keep_required_non_nullable and use_default are read (the
same scope that sets use_default_keep_required_non_nullable: bool = False), emit
a clear warning message (e.g., via logging.warning or click.echo) that explains
the flag is a no-op without --use-default and suggest enabling --use-default or
unsetting the flag; ensure this validation runs before any code generation logic
that depends on these flags.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/cli-reference/model-customization.md`:
- Line 40: Update the user-facing description for the CLI option
`--use-default-keep-required-non-nullable` to correct typos and hyphenation:
change "non nullable" to "non-nullable", correct any "non-nullale" misspelling,
and replace "optiona" with "optional" so the phrase reads e.g. "When using
default, keep required fields non-nullable/optional..." wherever that text
appears (including the other occurrences referenced).
- Around line 5296-5301: The OpenAPI "OpenAPI" example currently references a
missing example file (openapi/default_factory_keep_required_non_nullable.json)
and shows output that reflects the new keep-required-non-nullable behavior
instead of the baseline `--use-default` behavior; replace the placeholder with a
real, valid input JSON/YAML example that demonstrates the baseline
`--use-default` behavior and update the shown output to match that baseline, or
alternatively explicitly add the new flag (e.g., --keep-required-non-nullable)
to the example invocation and update both input and output to match the new
behavior; apply the same replacement/update to the parallel example block
covering the lines labeled 5304-5323 so both examples are consistent and use
actual files and outputs.
- Around line 5556-5558: The dataclasses example uses an invalid positional call
to dataclasses.field (shown as field(Model)); update the dataclasses snippet to
call dataclasses.field with keyword arguments, e.g., use
field(default_factory=Model) so the Model is provided via default_factory;
locate the dataclasses example that references field(...) and replace the
positional form with field(default_factory=Model).

In `@src/datamodel_code_generator/model/msgspec.py`:
- Around line 96-100: The predicate that suppresses UnsetType currently uses
"not (self.has_default and self.use_default_keep_required_non_nullable)" and
thus affects optional fields; update each predicate (the ones referencing
self.required, self.has_default, and
self.use_default_keep_required_non_nullable) to require the field be required as
well by changing the condition to "not (self.required and self.has_default and
self.use_default_keep_required_non_nullable)". Locate and update the three
occurrences that currently check self.required and the flag (around the existing
predicates at lines shown in the review) so the flag only applies when
self.required is true.

In `@tests/main/openapi/test_main_openapi.py`:
- Around line 5347-5353: Fix the typo "non-nullale" to "non-nullable" in the
user-facing docstrings and test descriptions (e.g., the option_description
triple-quoted string and the other occurrence around lines 5367-5371); also
standardize phrasing to "non-nullable/non-optional" where appropriate so
decorator docs and tests use consistent wording (search for the exact string
"non-nullale" and replace with "non-nullable" or "non-nullable/non-optional" in
the surrounding explanatory text).
- Around line 5357-5360: The model_outputs entries in the test module's
model_outputs mapping ("dataclass", "pydantic_v2", "msgspec") are pointing to
the wrong namespace prefix "main/jsonschema/..."; update those string values so
they target the OpenAPI test namespace (replace the "main/jsonschema/" prefix
with the correct "openapi/jsonschema/" prefix) so CLI-doc linking for this
option block points to the proper OpenAPI outputs.

---

Outside diff comments:
In `@src/datamodel_code_generator/parser/jsonschema.py`:
- Around line 2845-2862: The code currently sets nullable_override=False
whenever keep_non_nullable is true, but keep_non_nullable only checks required
and effective_has_default and can incorrectly clear schema-nullability; update
the condition so keep_non_nullable also verifies the source schema is
non-nullable (e.g., the schema's nullable flag or its type does not include
"null") before flipping required and before passing nullable_override=False into
get_object_field; in practice compute a boolean like source_is_non_nullable from
the existing field/schema metadata and change the logic that sets required and
nullable_override so nullable_override=False is only used when keep_non_nullable
and source_is_non_nullable are both true (leave nullable_override as None
otherwise).

---

Nitpick comments:
In `@docs/cli-reference/quick-reference.md`:
- Line 130: Replace the unhyphenated phrase "non nullable" with the correct
compound adjective "non-nullable" in the documentation entries that mention the
flag `--use-default-keep-required-non-nullable` (the table row description) and
the other occurrence referenced in the comment; update both text occurrences so
the descriptions read "non-nullable/optional" (or similar) to fix the
hyphenation.

In `@src/datamodel_code_generator/__main__.py`:
- Line 534: Add a runtime check after parsing flags to warn the user if
use_default_keep_required_non_nullable is True while use_default is False;
specifically, in the main argument-handling flow where
use_default_keep_required_non_nullable and use_default are read (the same scope
that sets use_default_keep_required_non_nullable: bool = False), emit a clear
warning message (e.g., via logging.warning or click.echo) that explains the flag
is a no-op without --use-default and suggest enabling --use-default or unsetting
the flag; ensure this validation runs before any code generation logic that
depends on these flags.

In `@src/datamodel_code_generator/arguments.py`:
- Around line 889-895: Update the help text for the field_options.add_argument
call that registers "--use-default-keep-required-non-nullable" to explicitly
state it only applies when "--use-default" is used; change the help string in
the field_options.add_argument invocation (the
--use-default-keep-required-non-nullable argument) to mention it is a modifier
for --use-default and will have no effect unless --use-default is also provided.

In `@src/datamodel_code_generator/prompt_data.py`:
- Line 123: Update the description text for the CLI flag
"--use-default-keep-required-non-nullable" in prompt_data.py to be clearer:
change the value from "When using default, keep required field non
nullable/optional." to something like "When using --use-default, keep required
fields with defaults as non-nullable." This targets the string literal mapped to
the key "--use-default-keep-required-non-nullable" so the help/documentation
reads unambiguously.
🪄 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: 8248e4be-25c1-4443-8f84-3166ffb4136a

📥 Commits

Reviewing files that changed from the base of the PR and between f0960e9 and c987f59.

⛔ Files ignored due to path filters (2)
  • docs/llms-full.txt is excluded by none and included by none
  • tests/data/openapi/default_factory_keep_required_non_nullable.yaml is excluded by !tests/data/**/*.yaml and included by none
📒 Files selected for processing (23)
  • docs/cli-reference/index.md
  • docs/cli-reference/model-customization.md
  • docs/cli-reference/quick-reference.md
  • src/datamodel_code_generator/__main__.py
  • src/datamodel_code_generator/_types/generate_config_dict.py
  • src/datamodel_code_generator/_types/parser_config_dicts.py
  • src/datamodel_code_generator/arguments.py
  • src/datamodel_code_generator/cli_options.py
  • src/datamodel_code_generator/config.py
  • src/datamodel_code_generator/model/base.py
  • src/datamodel_code_generator/model/msgspec.py
  • src/datamodel_code_generator/parser/base.py
  • src/datamodel_code_generator/parser/graphql.py
  • src/datamodel_code_generator/parser/jsonschema.py
  • src/datamodel_code_generator/parser/openapi.py
  • src/datamodel_code_generator/prompt_data.py
  • tests/data/expected/main/input_model/config_class.py
  • tests/data/expected/main/jsonschema/default_keep_required_non_nullable_dataclass.py
  • tests/data/expected/main/jsonschema/default_keep_required_non_nullable_msgspec.py
  • tests/data/expected/main/jsonschema/default_keep_required_non_nullable_pydantic_v2.py
  • tests/data/expected/main/openapi/use_default_keep_required_non_nullable.py
  • tests/main/openapi/test_main_openapi.py
  • tests/main/test_public_api_signature_baseline.py

Comment thread docs/cli-reference/model-customization.md Outdated
Comment thread docs/cli-reference/model-customization.md
Comment thread docs/cli-reference/model-customization.md Outdated
Comment thread src/datamodel_code_generator/model/msgspec.py Outdated
Comment thread tests/main/openapi/test_main_openapi.py Outdated
Comment thread tests/main/openapi/test_main_openapi.py Outdated
@GuillaumeSmaha GuillaumeSmaha force-pushed the add-default-on-required branch from c987f59 to 32912ac Compare April 14, 2026 14:47
The aim is to provide a way to keep the field non nullable/optional when --use-default is used

```yaml
    Pet:
      required:
        - id
        - name
      properties:
        id:
          type: integer
          format: int64
          default: 1
        name:
          type: string
        tag:
          type: string
```
wil become:
```python
class Pet(BaseModel):
    id: int = 1
    name: str
    tag: str | None = None
```
instead of (current implementation):
```python
class Pet(BaseModel):
    id: int | None = 1
    name: str
    tag: str | None = None
```
@GuillaumeSmaha GuillaumeSmaha force-pushed the add-default-on-required branch from 32912ac to f89d2b3 Compare April 14, 2026 14:47
@GuillaumeSmaha GuillaumeSmaha marked this pull request as ready for review April 14, 2026 15:46
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: 2

♻️ Duplicate comments (2)
docs/cli-reference/model-customization.md (2)

40-40: ⚠️ Potential issue | 🟡 Minor

Fix wording typo and contradiction in the new option description.

At Line 40 and Line 5579-5583, use non-nullable (hyphenated) and avoid non-nullable/optional phrasing, which is contradictory. The description should state non-nullable/non-optional (or required) consistently.

Also applies to: 5579-5583

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/cli-reference/model-customization.md` at line 40, The option description
for `--use-default-keep-required-non-nullable` contains a wording typo and a
contradictory phrase "non nullable/optional"; update both occurrences (the short
table entry and the longer description) to use the hyphenated term and a
consistent phrasing such as "non-nullable/non-optional" or "required" (e.g.,
replace "non nullable/optional" with "non-nullable/non-optional" and ensure
`non-nullable` is hyphenated wherever the option name or description appears).

5296-5350: ⚠️ Potential issue | 🟠 Major

--use-default example currently shows the new flag behavior, not baseline behavior.

At Line 5296-5350, the --use-default example output is non-nullable (number: conint(ge=0) = Field(1, ...)), which conflicts with the warning at Line 5279-5285 describing nullable behavior for baseline --use-default. Please align this section to true baseline output (or explicitly include the new flag in the command/example).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/cli-reference/model-customization.md` around lines 5296 - 5350, The
example for --use-default currently shows non-nullable output for Data.number;
update the example to match baseline behavior by making the generated field
nullable or explicitly show the new flag in the example command. Specifically,
change the Data model's number field from "number: conint(ge=0) = Field(1, ...)"
to a nullable form (e.g., "number: conint(ge=0) | None = Field(1,
description='Number')" or an Optional typing equivalent) so
Block.data/dataOptional reflect baseline nullability, or alternatively modify
the example invocation to include the new flag that enables non-nullable
defaults and keep the code block as-is; adjust the Data and Block model outputs
in the documentation accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/cli-reference/quick-reference.md`:
- Line 130: The description for the CLI flag
`--use-default-keep-required-non-nullable` is contradictory; update both
occurrences of this option so the wording is hyphenated and unambiguous — e.g.,
replace "non nullable/optional" with "non-nullable (non-optional / required)" so
the line reads that default usage keeps required fields non-nullable and
non-optional; ensure both instances of
`--use-default-keep-required-non-nullable` are changed to the same clarified
phrasing.

In `@src/datamodel_code_generator/model/pydantic_base.py`:
- Around line 207-208: The generator currently adds IMPORT_FIELD whenever
self.field is truthy even though the branch in the method (the branch using
self.required, self.has_default and self.use_default_keep_required_non_nullable
that returns repr_set_sorted(self.default) or repr(self.default)) can return a
plain literal; update the import logic so IMPORT_FIELD is only added when the
default is actually a Field(...) usage rather than a literal: change the
condition that adds IMPORT_FIELD to check self.field AND that the default is not
a plain literal (e.g., not an instance of basic literal types or explicitly
detect Field/FieldInfo), or alternatively only add IMPORT_FIELD when the code
path produces a Field expression; use the existing symbols (self.field,
self.default, repr_set_sorted, use_default_keep_required_non_nullable,
IMPORT_FIELD) to implement this guard.

---

Duplicate comments:
In `@docs/cli-reference/model-customization.md`:
- Line 40: The option description for `--use-default-keep-required-non-nullable`
contains a wording typo and a contradictory phrase "non nullable/optional";
update both occurrences (the short table entry and the longer description) to
use the hyphenated term and a consistent phrasing such as
"non-nullable/non-optional" or "required" (e.g., replace "non nullable/optional"
with "non-nullable/non-optional" and ensure `non-nullable` is hyphenated
wherever the option name or description appears).
- Around line 5296-5350: The example for --use-default currently shows
non-nullable output for Data.number; update the example to match baseline
behavior by making the generated field nullable or explicitly show the new flag
in the example command. Specifically, change the Data model's number field from
"number: conint(ge=0) = Field(1, ...)" to a nullable form (e.g., "number:
conint(ge=0) | None = Field(1, description='Number')" or an Optional typing
equivalent) so Block.data/dataOptional reflect baseline nullability, or
alternatively modify the example invocation to include the new flag that enables
non-nullable defaults and keep the code block as-is; adjust the Data and Block
model outputs in the documentation accordingly.
🪄 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: b5ed09df-56fb-4e2e-81c3-13f578e0001f

📥 Commits

Reviewing files that changed from the base of the PR and between c987f59 and 8d1a7db.

⛔ Files ignored due to path filters (2)
  • docs/llms-full.txt is excluded by none and included by none
  • tests/data/openapi/default_factory_keep_required_non_nullable.yaml is excluded by !tests/data/**/*.yaml and included by none
📒 Files selected for processing (25)
  • docs/cli-reference/index.md
  • docs/cli-reference/model-customization.md
  • docs/cli-reference/quick-reference.md
  • src/datamodel_code_generator/__main__.py
  • src/datamodel_code_generator/_types/generate_config_dict.py
  • src/datamodel_code_generator/_types/parser_config_dicts.py
  • src/datamodel_code_generator/arguments.py
  • src/datamodel_code_generator/cli_options.py
  • src/datamodel_code_generator/config.py
  • src/datamodel_code_generator/model/base.py
  • src/datamodel_code_generator/model/dataclass.py
  • src/datamodel_code_generator/model/msgspec.py
  • src/datamodel_code_generator/model/pydantic_base.py
  • src/datamodel_code_generator/parser/base.py
  • src/datamodel_code_generator/parser/graphql.py
  • src/datamodel_code_generator/parser/jsonschema.py
  • src/datamodel_code_generator/parser/openapi.py
  • src/datamodel_code_generator/prompt_data.py
  • tests/data/expected/main/input_model/config_class.py
  • tests/data/expected/main/openapi/default_keep_required_non_nullable_dataclass.py
  • tests/data/expected/main/openapi/default_keep_required_non_nullable_msgspec.py
  • tests/data/expected/main/openapi/default_keep_required_non_nullable_pydantic_v2.py
  • tests/data/expected/main/openapi/use_default_keep_required_non_nullable.py
  • tests/main/openapi/test_main_openapi.py
  • tests/main/test_public_api_signature_baseline.py
✅ Files skipped from review due to trivial changes (7)
  • src/datamodel_code_generator/_types/parser_config_dicts.py
  • src/datamodel_code_generator/parser/graphql.py
  • src/datamodel_code_generator/_types/generate_config_dict.py
  • src/datamodel_code_generator/prompt_data.py
  • tests/data/expected/main/openapi/default_keep_required_non_nullable_dataclass.py
  • tests/data/expected/main/openapi/default_keep_required_non_nullable_msgspec.py
  • tests/data/expected/main/openapi/default_keep_required_non_nullable_pydantic_v2.py
🚧 Files skipped from review as they are similar to previous changes (13)
  • tests/data/expected/main/input_model/config_class.py
  • src/datamodel_code_generator/model/base.py
  • src/datamodel_code_generator/parser/base.py
  • src/datamodel_code_generator/cli_options.py
  • src/datamodel_code_generator/main.py
  • src/datamodel_code_generator/parser/openapi.py
  • src/datamodel_code_generator/config.py
  • src/datamodel_code_generator/arguments.py
  • tests/main/test_public_api_signature_baseline.py
  • src/datamodel_code_generator/model/msgspec.py
  • src/datamodel_code_generator/parser/jsonschema.py
  • tests/main/openapi/test_main_openapi.py
  • tests/data/expected/main/openapi/use_default_keep_required_non_nullable.py

Comment thread docs/cli-reference/quick-reference.md Outdated
Comment thread src/datamodel_code_generator/model/pydantic_base.py
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 (3)
docs/cli-reference/quick-reference.md (1)

130-130: ⚠️ Potential issue | 🟡 Minor

Keep both quick-reference entries consistent and typo-free.

Both entries still use broken/ambiguous phrasing (non nullable/non-optionaloptional). Update both to the same clear wording, e.g., “keep required fields non-nullable and non-optional.”

Also applies to: 338-338

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/cli-reference/quick-reference.md` at line 130, The quick-reference entry
for the flag `--use-default-keep-required-non-nullable` contains a
typo/ambiguous phrase ("non nullable/non-optionaloptional"); update this and the
duplicate entry to a consistent, clear wording such as: "keep required fields
non-nullable and non-optional." Ensure both occurrences of the flag text in
quick-reference are replaced with the exact corrected phrase and preserve the
link target (`model-customization.md#use-default-keep-required-non-nullable`).
docs/cli-reference/model-customization.md (2)

40-40: ⚠️ Potential issue | 🟡 Minor

Fix contradictory/typo wording for the new option description.

The text is currently inconsistent and malformed (non nullable/..., non-optionaloptional, and non-nullable/optional). Please standardize to unambiguous wording like: “keep required fields non-nullable and non-optional (required).”

Also applies to: 5579-5583

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/cli-reference/model-customization.md` at line 40, The option description
for `--use-default-keep-required-non-nullable` is inconsistent and contains
typos; update its text to a clear, unambiguous phrase such as “keep required
fields non-nullable and non-optional (required)” wherever it appears (including
the other occurrence near lines 5579-5583), replacing variants like “non
nullable/non-opt...”, “non-optionaloptional”, or “non-nullable/optional” so the
wording is standardized across the document.

5296-5350: ⚠️ Potential issue | 🟠 Major

--use-default baseline example still shows keep-required behavior.

In the --use-default section, the generated outputs keep number non-nullable/non-optional (e.g., Line 5344), which contradicts the baseline behavior documented above (Line 5279-5286) and the implemented parser logic. Baseline --use-default should show required+default fields downgraded to optional/nullable unless --use-default-keep-required-non-nullable is also passed.

Also applies to: 5352-5396

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/cli-reference/model-customization.md` around lines 5296 - 5350, The
example in the `--use-default` section mistakenly retains a non-nullable
required field; update the generated output so fields with a default that were
originally required are shown as optional/nullable unless
`--use-default-keep-required-non-nullable` is present — specifically change the
Data model's `number` declaration in the "Pydantic v2" example to be
nullable/optional (i.e., represent `number` as optional/nullable with the
default preserved) and mirror the same fix for the duplicate example later in
the file; reference the symbol `Data.number` and the flags `--use-default` and
`--use-default-keep-required-non-nullable` when making the corrections.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@docs/cli-reference/model-customization.md`:
- Line 40: The option description for `--use-default-keep-required-non-nullable`
is inconsistent and contains typos; update its text to a clear, unambiguous
phrase such as “keep required fields non-nullable and non-optional (required)”
wherever it appears (including the other occurrence near lines 5579-5583),
replacing variants like “non nullable/non-opt...”, “non-optionaloptional”, or
“non-nullable/optional” so the wording is standardized across the document.
- Around line 5296-5350: The example in the `--use-default` section mistakenly
retains a non-nullable required field; update the generated output so fields
with a default that were originally required are shown as optional/nullable
unless `--use-default-keep-required-non-nullable` is present — specifically
change the Data model's `number` declaration in the "Pydantic v2" example to be
nullable/optional (i.e., represent `number` as optional/nullable with the
default preserved) and mirror the same fix for the duplicate example later in
the file; reference the symbol `Data.number` and the flags `--use-default` and
`--use-default-keep-required-non-nullable` when making the corrections.

In `@docs/cli-reference/quick-reference.md`:
- Line 130: The quick-reference entry for the flag
`--use-default-keep-required-non-nullable` contains a typo/ambiguous phrase
("non nullable/non-optionaloptional"); update this and the duplicate entry to a
consistent, clear wording such as: "keep required fields non-nullable and
non-optional." Ensure both occurrences of the flag text in quick-reference are
replaced with the exact corrected phrase and preserve the link target
(`model-customization.md#use-default-keep-required-non-nullable`).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 4cf73d8c-8a7a-406f-b1ca-03cebb96b97f

📥 Commits

Reviewing files that changed from the base of the PR and between 8d1a7db and 4f3817e.

⛔ Files ignored due to path filters (1)
  • docs/llms-full.txt is excluded by none and included by none
📒 Files selected for processing (6)
  • docs/cli-reference/model-customization.md
  • docs/cli-reference/quick-reference.md
  • src/datamodel_code_generator/arguments.py
  • src/datamodel_code_generator/model/pydantic_base.py
  • src/datamodel_code_generator/prompt_data.py
  • tests/main/openapi/test_main_openapi.py
✅ Files skipped from review due to trivial changes (1)
  • src/datamodel_code_generator/arguments.py
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/datamodel_code_generator/prompt_data.py
  • src/datamodel_code_generator/model/pydantic_base.py
  • tests/main/openapi/test_main_openapi.py

@GuillaumeSmaha
Copy link
Copy Markdown
Author

Ahah I just realize that --strict-nullable is almost the same. When I checked it, I was getting few different result.
I am going to put it back to draft in the mean time

@GuillaumeSmaha GuillaumeSmaha marked this pull request as draft April 14, 2026 19:25
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