Skip to content

Commit ec5376e

Browse files
authored
4717 Add update API for the ConfigParser (#4721)
[DLMED] add update API for config parser Signed-off-by: Nic Ma <nma@nvidia.com>
1 parent 345b8ae commit ec5376e

File tree

3 files changed

+20
-3
lines changed

3 files changed

+20
-3
lines changed

monai/bundle/config_parser.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,11 +178,27 @@ def get(self, id: str = "", default: Optional[Any] = None):
178178

179179
def set(self, config: Any, id: str = ""):
180180
"""
181-
Set config by ``id``. See also :py:meth:`__setitem__`.
181+
Set config by ``id``.
182+
183+
Args:
184+
config: config to set at location ``id``.
185+
id: id to specify the expected position. See also :py:meth:`__setitem__`.
182186
183187
"""
184188
self[id] = config
185189

190+
def update(self, pairs: Dict[str, Any]):
191+
"""
192+
Set the ``id`` and the corresponding config content in pairs, see also :py:meth:`__setitem__`.
193+
For example, ``parser.update({"train#epoch": 100, "train#lr": 0.02})``
194+
195+
Args:
196+
pairs: dictionary of `id` and config pairs.
197+
198+
"""
199+
for k, v in pairs.items():
200+
self[k] = v
201+
186202
def __contains__(self, id: Union[str, int]) -> bool:
187203
"""
188204
Returns True if `id` is stored in this configuration.

monai/bundle/scripts.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -372,8 +372,7 @@ def run(
372372
parser.read_meta(f=meta_file_)
373373

374374
# the rest key-values in the _args are to override config content
375-
for k, v in _args.items():
376-
parser[k] = v
375+
parser.update(pairs=_args)
377376

378377
# resolve and execute the specified runner expressions in the config, return the results
379378
return [parser.get_parsed_content(i, lazy=True, eval_expr=True, instantiate=True) for i in ensure_tuple(runner_id_)]

tests/test_config_parser.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,8 @@ def test_config_content(self):
104104
# test nested ids
105105
parser["dataset#_target_"] = "Dataset"
106106
self.assertEqual(parser["dataset#_target_"], "Dataset")
107+
parser.update({"dataset#_target_1": "Dataset1"})
108+
self.assertEqual(parser["dataset#_target_1"], "Dataset1")
107109
# test int id
108110
parser.set(["test1", "test2", "test3"])
109111
parser[1] = "test4"

0 commit comments

Comments
 (0)