Skip to content
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
16 changes: 3 additions & 13 deletions monai/utils/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,21 +250,11 @@ def has_option(obj, keywords: Union[str, Sequence[str]]) -> bool:
def get_package_version(dep_name, default="NOT INSTALLED or UNKNOWN VERSION."):
"""
Try to load package and get version. If not found, return `default`.

If the package was already loaded, leave it. If wasn't previously loaded, unload it.
"""
dep_ver = default
dep_already_loaded = dep_name not in sys.modules

dep, has_dep = optional_import(dep_name)
if has_dep:
if hasattr(dep, "__version__"):
dep_ver = dep.__version__
# if not previously loaded, unload it
if not dep_already_loaded:
del dep
del sys.modules[dep_name]
return dep_ver
if has_dep and hasattr(dep, "__version__"):
return dep.__version__
return default


def get_torch_version_tuple():
Expand Down
31 changes: 31 additions & 0 deletions tests/test_get_package_version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Copyright 2020 - 2021 MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest

from monai.utils.module import get_package_version


class TestGetVersion(unittest.TestCase):
def test_default(self):
output = get_package_version("42foobarnoexist")
self.assertTrue("UNKNOWN" in output)

output = get_package_version("numpy")
self.assertFalse("UNKNOWN" in output)

def test_msg(self):
output = get_package_version("42foobarnoexist", "test")
self.assertTrue("test" in output)


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