Skip to content

Commit af725d7

Browse files
authored
[DLMED] disable recursive macro (#4033)
Signed-off-by: Nic Ma <[email protected]>
1 parent 3947d4e commit af725d7

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

monai/bundle/config_parser.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,7 @@ def _do_resolve(self, config: Any, id: str = ""):
259259
`@##A` means `A` in the upper level. and replace the macro tokens with target content,
260260
The macro tokens start with "%", can be from another structured file, like:
261261
``"%default_net"``, ``"%/data/config.json#net"``.
262+
Note that the macro replacement doesn't support recursive macro tokens.
262263
263264
Args:
264265
config: input config file to resolve.
@@ -277,7 +278,7 @@ def _do_resolve(self, config: Any, id: str = ""):
277278
if config.startswith(MACRO_KEY):
278279
path, ids = ConfigParser.split_path_id(config[len(MACRO_KEY) :])
279280
parser = ConfigParser(config=self.get() if not path else ConfigParser.load_config_file(path))
280-
return self._do_resolve(config=deepcopy(parser[ids]))
281+
return parser[ids]
281282
return config
282283

283284
def resolve_macro_and_relative_ids(self):

tests/test_config_parser.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
# See the License for the specific language governing permissions and
1010
# limitations under the License.
1111

12+
import os
13+
import tempfile
1214
import unittest
1315
from unittest import skipUnless
1416

@@ -142,6 +144,16 @@ def test_relative_id(self, config):
142144
if isinstance(item, dict):
143145
self.assertEqual(str(item), str({"key": 1, "value1": 2, "value2": 2, "value3": [3, 4, 4, 105]}))
144146

147+
def test_macro_replace(self):
148+
with tempfile.TemporaryDirectory() as tempdir:
149+
another_file = os.path.join(tempdir, "another.json")
150+
ConfigParser.export_config_file(config={"E": 4}, filepath=another_file)
151+
# test macro with id, relative id, and macro in another file
152+
config = {"A": {"B": 1, "C": 2}, "D": [3, "%A#B", "%#0", f"%{another_file}#E"]}
153+
parser = ConfigParser(config=config)
154+
parser.resolve_macro_and_relative_ids()
155+
self.assertEqual(str(parser.get()), str({"A": {"B": 1, "C": 2}, "D": [3, 1, 3, 4]}))
156+
145157

146158
if __name__ == "__main__":
147159
unittest.main()

0 commit comments

Comments
 (0)