Skip to content

fix: respect nullable on array items with --strict-nullable#2713

Merged
koxudaxi merged 1 commit intomainfrom
fix/strict-nullable-array-items
Dec 20, 2025
Merged

fix: respect nullable on array items with --strict-nullable#2713
koxudaxi merged 1 commit intomainfrom
fix/strict-nullable-array-items

Conversation

@koxudaxi
Copy link
Copy Markdown
Owner

@koxudaxi koxudaxi commented Dec 20, 2025

Fixes: #1815

Summary by CodeRabbit

  • New Features

    • Enhanced support for nullable array items in JSON Schema with strict nullable mode, ensuring array elements are properly typed as optional when applicable.
  • Tests

    • Added test coverage for nullable array item handling in strict nullable mode with Pydantic v2.

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

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Dec 20, 2025

Walkthrough

This PR fixes handling of nullable array items in JSON Schema when using the --strict-nullable flag. It modifies the parser to wrap list-type schemas with nullable: true as optional types, generating list[str | None] instead of list[str] for nullable item arrays.

Changes

Cohort / File(s) Summary
Core logic
src/datamodel_code_generator/parser/jsonschema.py
Modified nullable handling for list-type schemas; when strict_nullable and obj.nullable are both true and obj.type is a list, the computed data type is now wrapped as a single optional type instead of returned directly.
Test schema and expectation
tests/data/jsonschema/nullable_array_items.yaml, tests/data/expected/main/jsonschema/nullable_array_items_strict_nullable.py
New test input schema defining four array properties with item-level nullability and nested arrays; corresponding expected output showing Pydantic model with proper nullable list item type annotations (e.g., list[str | None]).
Test function
tests/main/jsonschema/test_main_jsonschema.py
New test function test_main_nullable_array_items_strict_nullable that validates JSON Schema generation with --strict-nullable and --output-model-type pydantic_v2.BaseModel flags against the expected output.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • Logic change: Straightforward conditional wrapper for list-type nullable schemas; verify it correctly handles edge cases (nested arrays, mixed nullable/non-nullable items).
  • Test coverage: Validate that test cases adequately cover the fixed behavior (list with nullable items, non-nullable items, nested lists).

Possibly related PRs

  • PR #2537: Modifies array/tuple parsing logic in src/datamodel_code_generator/parser/jsonschema.py (prefixItems, parse_array_fields handling), affecting overlapping code regions.

Suggested labels

safe-to-fix

Suggested reviewers

  • ilovelinux

Poem

🐰 Arrays once bland now bloom with care,
Each nullable item gets its pair,
With strict-nullable standing guard,
Optional types make code less hard,
Hopping through schemas, clean and fair! ✨

Pre-merge checks and finishing touches

✅ 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 accurately summarizes the main change: fixing nullable array items to be respected when using the --strict-nullable flag.
Linked Issues check ✅ Passed The changes fully implement the requirement from issue #1815: nullable array items now generate as Optional types (list[str | None]) when --strict-nullable is enabled.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing the fix for issue #1815, with no extraneous modifications detected.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/strict-nullable-array-items

📜 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 e3a2cf5 and 9d10b39.

📒 Files selected for processing (4)
  • src/datamodel_code_generator/parser/jsonschema.py (1 hunks)
  • tests/data/expected/main/jsonschema/nullable_array_items_strict_nullable.py (1 hunks)
  • tests/data/jsonschema/nullable_array_items.yaml (1 hunks)
  • tests/main/jsonschema/test_main_jsonschema.py (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
src/datamodel_code_generator/parser/jsonschema.py (3)
src/datamodel_code_generator/parser/base.py (1)
  • data_type (978-980)
src/datamodel_code_generator/types.py (1)
  • nullable (280-282)
src/datamodel_code_generator/model/base.py (1)
  • nullable (684-686)
tests/main/jsonschema/test_main_jsonschema.py (2)
tests/test_main_kr.py (1)
  • output_file (44-46)
tests/main/conftest.py (2)
  • output_file (94-96)
  • run_main_and_assert (196-352)
⏰ 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). (8)
  • GitHub Check: 3.12 on Windows
  • GitHub Check: py312-isort5 on Ubuntu
  • GitHub Check: 3.14 on Windows
  • GitHub Check: 3.13 on Windows
  • GitHub Check: 3.10 on Windows
  • GitHub Check: 3.11 on Windows
  • GitHub Check: benchmarks
  • GitHub Check: Analyze (python)
🔇 Additional comments (4)
src/datamodel_code_generator/parser/jsonschema.py (1)

1071-1074: LGTM! Fix correctly wraps nullable item types as Optional.

The change appropriately handles nullable array items when --strict-nullable is enabled. By wrapping the data type as optional at the item level, arrays with nullable: true items will now generate list[str | None] instead of list[str], which matches the expected behavior described in issue #1815.

The placement is correct since this executes after list-type handling (lines 1066-1070), ensuring it applies to individual item types rather than the array container itself.

tests/data/jsonschema/nullable_array_items.yaml (1)

1-27: Well-designed test schema with comprehensive coverage.

The schema effectively tests the nullable array items fix across multiple scenarios:

  • Different primitive types (string, integer, number)
  • Nullable vs. non-nullable items (list3 serves as a control case)
  • Nested arrays with nullable items

This provides thorough validation that the fix works correctly for various type combinations.

tests/data/expected/main/jsonschema/nullable_array_items_strict_nullable.py (1)

10-14: Expected output correctly reflects strict nullable behavior for array items.

The generated types accurately represent the fix:

  • list[str | None] and list[int | None] correctly make nullable items optional
  • list[str] for list3 confirms non-nullable items remain non-optional
  • list[list[float | None]] correctly applies nullable at the item level in nested arrays

The output validates that the fix works as intended per issue #1815.

tests/main/jsonschema/test_main_jsonschema.py (1)

4523-4537: LGTM! Well-structured test for nullable array items fix.

The test properly validates the fix for issue #1815, ensuring that array items with nullable: true are generated as list[str | None] instead of list[str] when using the --strict-nullable flag. The test follows established patterns in the file and uses appropriate fixtures and helper functions.


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.

@codecov
Copy link
Copy Markdown

codecov Bot commented Dec 20, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.34%. Comparing base (e3a2cf5) to head (9d10b39).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2713   +/-   ##
=======================================
  Coverage   99.34%   99.34%           
=======================================
  Files          81       81           
  Lines       11534    11540    +6     
  Branches     1387     1388    +1     
=======================================
+ Hits        11458    11464    +6     
  Misses         45       45           
  Partials       31       31           
Flag Coverage Δ
unittests 99.34% <100.00%> (+<0.01%) ⬆️

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.

@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented Dec 20, 2025

CodSpeed Performance Report

Merging #2713 will not alter performance

Comparing fix/strict-nullable-array-items (9d10b39) with main (e3a2cf5)

Summary

✅ 52 untouched
🆕 1 new
⏩ 10 skipped1

Benchmarks breakdown

Benchmark BASE HEAD Efficiency
🆕 test_main_nullable_array_items_strict_nullable N/A 54.6 ms N/A

Footnotes

  1. 10 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.

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.

nullable array items are not defined as Optional, despite using --strict-nullable

1 participant