Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
^^^^^
- Choices with an int type not working correctly (`#827
<https://github.com/omni-us/jsonargparse/pull/827>`__).
- Union of dataclasses not discarding parameters on class change (`#833
<https://github.com/omni-us/jsonargparse/pull/833>`__).


v4.45.0 (2025-12-26)
Expand Down
10 changes: 7 additions & 3 deletions jsonargparse/_typehints.py
Original file line number Diff line number Diff line change
Expand Up @@ -1063,11 +1063,15 @@ def adapt_typehints(
prev_implicit_defaults = True

if isinstance(prev_val, (dict, Namespace)) and "class_path" not in prev_val:
# implicit prev_val class_path and init_args
prev_val = Namespace(class_path=get_import_path(typehint), init_args=Namespace(prev_val))
# implicit prev_val init_args
prev_val = Namespace(class_path=None, init_args=Namespace(prev_val))

val_input = val
val = subclass_spec_as_namespace(val, prev_val)
if isinstance(prev_val, (dict, Namespace)) and prev_val["class_path"] is None:
type_class_path = Namespace(class_path=get_import_path(typehint))
val = subclass_spec_as_namespace(val, type_class_path)
else:
val = subclass_spec_as_namespace(val, prev_val)
if val and not is_subclass_spec(val) and "init_args" not in val:
# implicit val class_path
val = Namespace(class_path=get_import_path(typehint), init_args=val)
Expand Down
30 changes: 30 additions & 0 deletions jsonargparse_tests/test_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -686,6 +686,36 @@ def test_class_path_union_dataclasses(parser):
assert json_or_yaml_load(parser.dump(cfg))["union"] == {"p1": "x", "p2": 0}


@dataclasses.dataclass
class SubA:
a: int = 2


@dataclasses.dataclass
class SubB:
b: float = 3.4


@dataclasses.dataclass
class SubAorB:
a_or_b: Union[SubA, SubB] = dataclasses.field(default_factory=SubA)


def test_union_dataclasses(parser):
parser.add_class_arguments(SubAorB, "data")

cfg = parser.parse_args([])
init = parser.instantiate_classes(cfg)
assert isinstance(init.data, SubAorB)
assert isinstance(init.data.a_or_b, SubA)

cfg = parser.parse_args(["--data.a_or_b.b=4"])
assert cfg.data.a_or_b == Namespace(b=4.0)
init = parser.instantiate_classes(cfg)
assert isinstance(init.data, SubAorB)
assert isinstance(init.data.a_or_b, SubB)


if type_alias_type:
IntOrString = type_alias_type("IntOrString", Union[int, str])

Expand Down
Loading