diff --git a/monai/bundle/config_item.py b/monai/bundle/config_item.py index f3d1cf69fd..c6da0a73de 100644 --- a/monai/bundle/config_item.py +++ b/monai/bundle/config_item.py @@ -18,6 +18,7 @@ from abc import ABC, abstractmethod from collections.abc import Mapping, Sequence from importlib import import_module +from pprint import pformat from typing import Any from monai.bundle.utils import EXPR_KEY @@ -157,7 +158,7 @@ def get_config(self): return self.config def __repr__(self) -> str: - return str(self.config) + return f"{type(self).__name__}: \n{pformat(self.config)}" class ConfigComponent(ConfigItem, Instantiable): @@ -291,7 +292,7 @@ def instantiate(self, **kwargs: Any) -> object: try: return instantiate(modname, mode, **args) except Exception as e: - raise RuntimeError(f"Failed to instantiate {self}.") from e + raise RuntimeError(f"Failed to instantiate {self}") from e class ConfigExpression(ConfigItem): @@ -372,7 +373,10 @@ def evaluate(self, globals: dict | None = None, locals: dict | None = None) -> s warnings.warn(f"the new global variable `{k}` conflicts with `self.globals`, override it.") globals_[k] = v if not run_debug: - return eval(value[len(self.prefix) :], globals_, locals) + try: + return eval(value[len(self.prefix) :], globals_, locals) + except Exception as e: + raise RuntimeError(f"Failed to evaluate {self}") from e warnings.warn( f"\n\npdb: value={value}\n" f"See also Debugger commands documentation: https://docs.python.org/3/library/pdb.html\n" diff --git a/tests/test_config_item.py b/tests/test_config_item.py index 3d1272719a..cb1e7ad552 100644 --- a/tests/test_config_item.py +++ b/tests/test_config_item.py @@ -128,6 +128,10 @@ def test_is_import_stmt(self, stmt, expected): flag = expr.is_import_statement(expr.config) self.assertEqual(flag, expected) + def test_error_expr(self): + with self.assertRaisesRegex(RuntimeError, r"1\+\[\]"): + ConfigExpression(id="", config="$1+[]").evaluate() + if __name__ == "__main__": unittest.main()