From 8a6f6fa25ca30c9180a92f2d62ec779bf3b4bf02 Mon Sep 17 00:00:00 2001 From: Nic Ma Date: Thu, 31 Mar 2022 18:34:50 +0800 Subject: [PATCH] [DLMED] disable recursive macro Signed-off-by: Nic Ma --- monai/bundle/config_parser.py | 3 ++- tests/test_config_parser.py | 12 ++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/monai/bundle/config_parser.py b/monai/bundle/config_parser.py index a9107a10e9..4f919a383a 100644 --- a/monai/bundle/config_parser.py +++ b/monai/bundle/config_parser.py @@ -259,6 +259,7 @@ def _do_resolve(self, config: Any, id: str = ""): `@##A` means `A` in the upper level. and replace the macro tokens with target content, The macro tokens start with "%", can be from another structured file, like: ``"%default_net"``, ``"%/data/config.json#net"``. + Note that the macro replacement doesn't support recursive macro tokens. Args: config: input config file to resolve. @@ -277,7 +278,7 @@ def _do_resolve(self, config: Any, id: str = ""): if config.startswith(MACRO_KEY): path, ids = ConfigParser.split_path_id(config[len(MACRO_KEY) :]) parser = ConfigParser(config=self.get() if not path else ConfigParser.load_config_file(path)) - return self._do_resolve(config=deepcopy(parser[ids])) + return parser[ids] return config def resolve_macro_and_relative_ids(self): diff --git a/tests/test_config_parser.py b/tests/test_config_parser.py index 8b1076b1f7..9c727c29ac 100644 --- a/tests/test_config_parser.py +++ b/tests/test_config_parser.py @@ -9,6 +9,8 @@ # See the License for the specific language governing permissions and # limitations under the License. +import os +import tempfile import unittest from unittest import skipUnless @@ -142,6 +144,16 @@ def test_relative_id(self, config): if isinstance(item, dict): self.assertEqual(str(item), str({"key": 1, "value1": 2, "value2": 2, "value3": [3, 4, 4, 105]})) + def test_macro_replace(self): + with tempfile.TemporaryDirectory() as tempdir: + another_file = os.path.join(tempdir, "another.json") + ConfigParser.export_config_file(config={"E": 4}, filepath=another_file) + # test macro with id, relative id, and macro in another file + config = {"A": {"B": 1, "C": 2}, "D": [3, "%A#B", "%#0", f"%{another_file}#E"]} + parser = ConfigParser(config=config) + parser.resolve_macro_and_relative_ids() + self.assertEqual(str(parser.get()), str({"A": {"B": 1, "C": 2}, "D": [3, 1, 3, 4]})) + if __name__ == "__main__": unittest.main()