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

6976 improve config expr error msg #6977

Merged
merged 1 commit into from
Sep 13, 2023
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
10 changes: 7 additions & 3 deletions monai/bundle/config_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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"
Expand Down
4 changes: 4 additions & 0 deletions tests/test_config_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()