diff --git a/src/python/jw/util/load_yaml.py b/src/python/jw/util/load_yaml.py index ef5292b..ef01d7b 100644 --- a/src/python/jw/util/load_yaml.py +++ b/src/python/jw/util/load_yaml.py @@ -235,7 +235,9 @@ def _expand_links_recursive( if link_key in resolving: raise ValueError(f"Cyclic link detected: {link_spec!r}") if link_key in resolved: - base_value: Any = resolved[link_key] + # Deepcopy so that cached results are not aliased into + # multiple places of the output tree + base_value: Any = deepcopy(resolved[link_key]) else: resolving.add(link_key) _, _, target_path, target_value = _resolve_link( @@ -274,7 +276,9 @@ def _expand_links_recursive( if link_key in resolving: raise ValueError(f"Cyclic link detected: {link_spec!r}") if link_key in resolved: - return resolved[link_key] + # Deepcopy so that cached results are not aliased into + # multiple places of the output tree + return deepcopy(resolved[link_key]) resolving.add(link_key) is_named, name, target_path, target_value = _resolve_link( diff --git a/test/unit/python/jw/util/load_yaml/test.py b/test/unit/python/jw/util/load_yaml/test.py index b99240f..1d293d1 100644 --- a/test/unit/python/jw/util/load_yaml/test.py +++ b/test/unit/python/jw/util/load_yaml/test.py @@ -621,6 +621,22 @@ class TestEdgeCases: assert data['a'] == 'val' assert data['b'] == 'val' + def test_cached_link_expansion_not_aliased(self, yaml_file: Callable) -> None: + """Link results shared via the memoisation cache are independent.""" + data = load_yaml( + yaml_file( + 'target:\n' + ' x: 1\n' + 'link_b:\n' + ' jw.link: target\n' + 'link_a:\n' + ' jw.link: link_b\n' + ) + ) + data['link_a']['x'] = 99 + assert data['link_b']['x'] == 1 + assert data['target']['x'] == 1 + def test_named_link_to_list(self, yaml_file: Callable) -> None: data = load_yaml( yaml_file('target:\n - x\n - y\nlink:\n jw.link: items|target\n')