Skip to content

Commit a77de4a

Browse files
authored
5931 Fix config parsing issue for substring reference (#5932)
Fixes #5931 . ### Description This PR fixed the bundle config parsing issue for substring reference. ### Types of changes <!--- Put an `x` in all the boxes that apply, and remove the not applicable items --> - [x] Non-breaking change (fix or new feature that would not break existing functionality). - [ ] Breaking change (fix or new feature that would cause existing functionality to change). - [ ] New tests added to cover the changes. - [ ] Integration tests passed locally by running `./runtests.sh -f -u --net --coverage`. - [ ] Quick tests passed locally by running `./runtests.sh --quick --unittests --disttests`. - [ ] In-line docstrings updated. - [ ] Documentation updated, tested `make html` command in the `docs/` folder. --------- Signed-off-by: Nic Ma <nma@nvidia.com>
1 parent 3c8f6c6 commit a77de4a

File tree

2 files changed

+10
-0
lines changed

2 files changed

+10
-0
lines changed

monai/bundle/reference_resolver.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,9 @@ def update_refs_pattern(cls, value: str, refs: dict) -> str:
222222
"""
223223
# regular expression pattern to match "@XXX" or "@XXX#YYY"
224224
result = cls.id_matcher.findall(value)
225+
# reversely sort the matched references by length
226+
# and handle the longer first in case a reference item is substring of another longer item
227+
result.sort(key=len, reverse=True)
225228
value_is_expr = ConfigExpression.is_expression(value)
226229
for item in result:
227230
# only update reference when string starts with "$" or the whole content is "@XXX"

tests/test_config_parser.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,8 @@ def __call__(self, a, b):
107107

108108
TEST_CASE_4 = [{"A": 1, "B": "@A", "C": "@D", "E": "$'test' + '@F'"}]
109109

110+
TEST_CASE_5 = [{"training": {"A": 1, "A_B": 2}, "total": "$@training#A + @training#A_B + 1"}, 4]
111+
110112

111113
class TestConfigParser(unittest.TestCase):
112114
def test_config_content(self):
@@ -296,6 +298,11 @@ def test_builtin(self):
296298
config = {"import statements": "$import math", "calc": {"_target_": "math.isclose", "a": 0.001, "b": 0.001}}
297299
self.assertEqual(ConfigParser(config).calc, True)
298300

301+
@parameterized.expand([TEST_CASE_5])
302+
def test_substring_reference(self, config, expected):
303+
parser = ConfigParser(config=config)
304+
self.assertEqual(parser.get_parsed_content("total"), expected)
305+
299306

300307
if __name__ == "__main__":
301308
unittest.main()

0 commit comments

Comments
 (0)