Skip to content

Commit 92a32c0

Browse files
authored
fix: respect nullable on array items with --strict-nullable (#2713)
1 parent e3a2cf5 commit 92a32c0

File tree

4 files changed

+62
-1
lines changed

4 files changed

+62
-1
lines changed

src/datamodel_code_generator/parser/jsonschema.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1068,7 +1068,10 @@ def _get_data_type(type_: str, format__: str) -> DataType:
10681068
data_types=[_get_data_type(t, obj.format or "default") for t in obj.type if t != "null"],
10691069
is_optional="null" in obj.type,
10701070
)
1071-
return _get_data_type(obj.type, obj.format or "default")
1071+
data_type = _get_data_type(obj.type, obj.format or "default")
1072+
if self.strict_nullable and obj.nullable:
1073+
return self.data_type(data_types=[data_type], is_optional=True)
1074+
return data_type
10721075

10731076
def get_ref_data_type(self, ref: str) -> DataType:
10741077
"""Get a data type from a reference string."""
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# generated by datamodel-codegen:
2+
# filename: nullable_array_items.yaml
3+
# timestamp: 2019-07-26T00:00:00+00:00
4+
5+
from __future__ import annotations
6+
7+
from pydantic import BaseModel
8+
9+
10+
class Model(BaseModel):
11+
list1: list[str | None]
12+
list2: list[int | None]
13+
list3: list[str]
14+
nested_list: list[list[float | None]]
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
properties:
2+
list1:
3+
type: array
4+
items:
5+
type: string
6+
nullable: true
7+
list2:
8+
type: array
9+
items:
10+
type: integer
11+
nullable: true
12+
list3:
13+
type: array
14+
items:
15+
type: string
16+
nested_list:
17+
type: array
18+
items:
19+
type: array
20+
items:
21+
type: number
22+
nullable: true
23+
required:
24+
- list1
25+
- list2
26+
- list3
27+
- nested_list

tests/main/jsonschema/test_main_jsonschema.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4518,3 +4518,20 @@ def test_main_allof_root_model_constraints_none(output_file: Path) -> None:
45184518
expected_file="allof_root_model_constraints.py",
45194519
extra_args=["--allof-merge-mode", "none"],
45204520
)
4521+
4522+
4523+
@pytest.mark.benchmark
4524+
def test_main_nullable_array_items_strict_nullable(output_file: Path) -> None:
4525+
"""Test nullable array items with strict-nullable flag (issue #1815)."""
4526+
run_main_and_assert(
4527+
input_path=JSON_SCHEMA_DATA_PATH / "nullable_array_items.yaml",
4528+
output_path=output_file,
4529+
input_file_type="jsonschema",
4530+
assert_func=assert_file_content,
4531+
expected_file="nullable_array_items_strict_nullable.py",
4532+
extra_args=[
4533+
"--strict-nullable",
4534+
"--output-model-type",
4535+
"pydantic_v2.BaseModel",
4536+
],
4537+
)

0 commit comments

Comments
 (0)