Skip to content

Commit 4b956d4

Browse files
DianLiImauvilsa
andauthored
Fix failure when a link target has an undefined parent (#668)
--------- Co-authored-by: Mauricio Villegas <[email protected]>
1 parent f786412 commit 4b956d4

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

CHANGELOG.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ Fixed
2727
<https://github.com/omni-us/jsonargparse/pull/662>`__).
2828
- Pydantic discriminated unions handled incorrectly (`#667
2929
<https://github.com/omni-us/jsonargparse/pull/667>`__).
30+
- Failure when a link target has an undefined parent (`#668
31+
<https://github.com/omni-us/jsonargparse/pull/668>`__)
3032

3133

3234
v4.36.0 (2025-01-17)

jsonargparse/_typehints.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1374,7 +1374,10 @@ def adapt_class_type(
13741374

13751375
parent_key, key = target.split(split, maxsplit=1)
13761376

1377-
action = next(a for a in parser._actions if a.dest == parent_key)
1377+
try:
1378+
action = next(a for a in parser._actions if a.dest == parent_key)
1379+
except StopIteration:
1380+
continue
13781381

13791382
sub_add_kwargs = getattr(action, "sub_add_kwargs")
13801383
sub_add_kwargs.setdefault("linked_targets", set())

jsonargparse_tests/test_link_arguments.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1139,6 +1139,27 @@ def test_on_instantiate_linking_deep_targets_mapping(parser, tmp_path):
11391139
assert isinstance(config_init["b"].a_map["name"].d, DeepD)
11401140

11411141

1142+
def test_on_instantiate_linking_deep_targets_undefined_parent(parser, tmp_path):
1143+
config = {
1144+
"b": {
1145+
"class_path": f"{__name__}.DeepBSuper",
1146+
},
1147+
"c": {},
1148+
}
1149+
config_path = tmp_path / "config.yaml"
1150+
config_path.write_text(json_or_yaml_dump(config))
1151+
1152+
parser.add_argument("--config", action="config")
1153+
parser.add_subclass_arguments(DeepBSuper, nested_key="b", required=True)
1154+
parser.add_class_arguments(DeepC, nested_key="c")
1155+
# .init_args.a is undefined in DeepBSuper
1156+
parser.link_arguments("c", "b.init_args.a.init_args.d", compute_fn=DeepC.fn, apply_on="instantiate")
1157+
1158+
config = parser.parse_args([f"--config={config_path}"])
1159+
config_init = parser.instantiate_classes(config)
1160+
assert isinstance(config_init["b"], DeepBSuper)
1161+
1162+
11421163
class DeepTarget:
11431164
def __init__(self, a: int, b: int) -> None:
11441165
self.a = a

0 commit comments

Comments
 (0)