Skip to content

Commit f7aa49f

Browse files
authored
Fix List type incorrectly using defaults from previous item (#560)
1 parent c634a88 commit f7aa49f

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

CHANGELOG.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ Fixed
1919
^^^^^
2020
- ``dict`` types not correctly forwarding previous nested values when parsing
2121
(`#559 <https://github.com/omni-us/jsonargparse/pull/559>`__).
22+
- ``List`` type incorrectly using defaults from previous item (`#560
23+
<https://github.com/omni-us/jsonargparse/pull/560>`__).
2224

2325

2426
v4.32.0 (2024-07-19)

jsonargparse/_typehints.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -871,10 +871,11 @@ def adapt_typehints(
871871
elif not isinstance(val, list):
872872
raise_unexpected_value(f"Expected a {typehint_origin}", val)
873873
if subtypehints is not None:
874-
adapt_kwargs_n = adapt_kwargs
875874
for n, v in enumerate(val):
876875
if isinstance(prev_val, list) and len(prev_val) == len(val):
877-
adapt_kwargs_n = {**adapt_kwargs, "prev_val": prev_val[n]}
876+
adapt_kwargs_n = {**deepcopy(adapt_kwargs), "prev_val": prev_val[n]}
877+
else:
878+
adapt_kwargs_n = deepcopy(adapt_kwargs)
878879
val[n] = adapt_typehints(v, subtypehints[0], list_item=True, **adapt_kwargs_n)
879880

880881
# Dict, Mapping

jsonargparse_tests/test_dataclass_like.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,18 @@ def test_list_nested_optional_dataclass(parser):
203203
assert cfg.b == [Namespace(a=Namespace(x=1))]
204204

205205

206+
@dataclasses.dataclass
207+
class ItemData:
208+
x: int = 1
209+
y: str = "one"
210+
211+
212+
def test_list_append_defaults(parser):
213+
parser.add_argument("--list", type=List[ItemData])
214+
cfg = parser.parse_args(["--list+={}", '--list+={"x":2,"y":"two"}', '--list+={"x":3}'])
215+
assert cfg.list == [Namespace(x=1, y="one"), Namespace(x=2, y="two"), Namespace(x=3, y="one")]
216+
217+
206218
def test_add_argument_dataclass_type(parser):
207219
parser.add_argument("--b", type=DataClassB, default=DataClassB(b1=7.0))
208220
cfg = parser.get_defaults()

0 commit comments

Comments
 (0)