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
3 changes: 2 additions & 1 deletion monai/bundle/config_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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):
Expand Down
12 changes: 12 additions & 0 deletions tests/test_config_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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()