Skip to content

Commit

Permalink
Fix dataclass single parameter change incorrectly resetting previous …
Browse files Browse the repository at this point in the history
…values (#471)
  • Loading branch information
mauvilsa authored Mar 13, 2024
1 parent 14456c2 commit 7a4a3dc
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ Fixed
<https://github.com/omni-us/jsonargparse/issues/465>`__).
- Optional callable that returns a class instance with a lambda default,
produces an invalid string default.
- dataclass single parameter change incorrectly resetting previous values (`#464
<https://github.com/omni-us/jsonargparse/issues/464>`__).


v4.27.5 (2024-02-12)
Expand Down
3 changes: 2 additions & 1 deletion jsonargparse/_typehints.py
Original file line number Diff line number Diff line change
Expand Up @@ -863,7 +863,8 @@ def adapt_typehints(
elif isinstance(val, (dict, Namespace)):
val = parser.parse_object(val, defaults=sub_defaults.get() or list_item)
elif isinstance(val, NestedArg):
val = parser.parse_args([f"--{val.key}={val.val}"])
prev_val = prev_val if isinstance(prev_val, Namespace) else None
val = parser.parse_args([f"--{val.key}={val.val}"], namespace=prev_val)
else:
raise_unexpected_value(f"Type {typehint} expects a dict or Namespace", val)

Expand Down
15 changes: 15 additions & 0 deletions jsonargparse_tests/test_dataclass_like.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import yaml

from jsonargparse import (
ActionConfigFile,
ArgumentError,
ArgumentParser,
Namespace,
Expand Down Expand Up @@ -359,6 +360,20 @@ def test_optional_dataclass_type_null_value():
assert cfg == parser_optional_data.instantiate_classes(cfg)


@dataclasses.dataclass
class SingleParamChange:
p1: int = 0
p2: int = 0


def test_optional_dataclass_single_param_change(parser):
parser.add_argument("--config", action=ActionConfigFile)
parser.add_argument("--data", type=Optional[SingleParamChange])
config = {"data": {"p1": 1}}
cfg = parser.parse_args([f"--config={config}", "--data.p2=2"])
assert cfg.data == Namespace(p1=1, p2=2)


@dataclasses.dataclass
class ModelConfig:
data: Optional[Dict[str, Any]] = None
Expand Down

0 comments on commit 7a4a3dc

Please sign in to comment.