Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

3482 Disable recursive macro replacement in config #4033

Merged
merged 6 commits into from
Mar 31, 2022
Merged
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
@@ -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):
12 changes: 12 additions & 0 deletions tests/test_config_parser.py
Original file line number Diff line number Diff line change
@@ -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()