Skip to content

Commit a006f8b

Browse files
committed
Preserve ImportError kwargs in OptionalImportError; record version hints only for known version checkers
1 parent 5edd731 commit a006f8b

2 files changed

Lines changed: 37 additions & 6 deletions

File tree

‎monai/utils/module.py‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -316,11 +316,13 @@ class OptionalImportError(ImportError):
316316
msg: the error message.
317317
pkg_name: name of the missing package that caused the import error, if known.
318318
It is used to provide installation hints to the users. Defaults to ``None``.
319+
name: name of the module whose import failed, see ``ImportError``. Defaults to ``None``.
320+
path: path of the file whose import failed, see ``ImportError``. Defaults to ``None``.
319321
320322
"""
321323

322-
def __init__(self, msg: str = "", pkg_name: str | None = None):
323-
super().__init__(msg)
324+
def __init__(self, msg: str = "", pkg_name: str | None = None, name: str | None = None, path: str | None = None):
325+
super().__init__(msg, name=name, path=path)
324326
self.pkg_name = pkg_name
325327

326328

@@ -478,7 +480,8 @@ def require_pkg(
478480
OptionalImportError: When ``raise_error`` is True and the required package is not installed or its
479481
version doesn't match the requirement. The error records the name of the package to install
480482
in ``pkg_name``, with the required version constraint appended when ``version`` is specified
481-
(e.g. ``itk>=5.2``), so that installation hints install a compatible version.
483+
and the ``version_checker`` is ``min_version`` or ``exact_version`` (e.g. ``itk>=5.2``),
484+
so that installation hints install a compatible version.
482485
483486
"""
484487

@@ -494,9 +497,12 @@ def _wrapper(*args, **kwargs):
494497
if raise_error:
495498
name = pkg_name
496499
if version:
497-
# record the version constraint so that installation hints install a compatible
498-
# version; `>=` is assumed for any `version_checker` other than `exact_version`
499-
name = f"{pkg_name}{'==' if version_checker is exact_version else '>='}{version}"
500+
if version_checker is min_version:
501+
name = f"{pkg_name}>={version}"
502+
elif version_checker is exact_version:
503+
name = f"{pkg_name}=={version}"
504+
# a custom version checker may enforce any constraint format (e.g. an upper
505+
# bound), so no version constraint is recorded for it in the install hint
500506
raise OptionalImportError(err_msg, pkg_name=name)
501507
else:
502508
warnings.warn(err_msg)

‎tests/utils/test_require_pkg.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,16 @@
1818

1919
class TestRequirePkg(unittest.TestCase):
2020

21+
def test_optional_import_error_kwargs(self):
22+
# the keywords inherited from ImportError must keep working alongside pkg_name
23+
err = OptionalImportError("missing dependency", name="PIL", path="/some/path")
24+
self.assertIsNone(err.pkg_name)
25+
self.assertEqual(err.name, "PIL")
26+
self.assertEqual(err.path, "/some/path")
27+
self.assertIn("missing dependency", str(err))
28+
# positional arguments keep their original meaning: (msg, pkg_name)
29+
self.assertEqual(OptionalImportError("msg", "pkg").pkg_name, "pkg")
30+
2131
def test_class(self):
2232

2333
@require_pkg(pkg_name="torch", version="1.4", version_checker=min_version)
@@ -87,6 +97,21 @@ def test_func(x):
8797

8898
self.assertEqual(cm.exception.pkg_name, "test123==1.2")
8999

100+
def test_custom_checker_exception(self):
101+
# a custom version checker has no known constraint format, so no version hint is recorded
102+
def custom_checker(the_module, version_str):
103+
return False
104+
105+
with self.assertRaises(OptionalImportError) as cm:
106+
107+
@require_pkg(pkg_name="torch", version="10000", version_checker=custom_checker)
108+
def test_func(x):
109+
return x
110+
111+
test_func(x=None)
112+
113+
self.assertEqual(cm.exception.pkg_name, "torch")
114+
90115
def test_func_exception(self):
91116
with self.assertRaises(OptionalImportError):
92117

0 commit comments

Comments
 (0)