Add importutils.import_any method
Method refactored from several dashboard projects including solum, cerberus and sticks. Inclusion in oslo.utils.importutils will enable remove the duplicated code and entire class in projects that only include this one method. Replaced original RuntimeError exception with ImportError to be consistent with current oslo.utils library. Change-Id: I85cb9cc0d9d58bc248cce3048b730bd387f48936
This commit is contained in:
parent
7e45bcc47d
commit
9e28e81216
@ -91,3 +91,21 @@ def try_import(import_str, default=None):
|
||||
return import_module(import_str)
|
||||
except ImportError:
|
||||
return default
|
||||
|
||||
|
||||
def import_any(module, *modules):
|
||||
"""Try to import a module from a list of modules.
|
||||
|
||||
:param modules: A list of modules to try and import
|
||||
:returns: The first module found that can be imported
|
||||
:raises ImportError: If no modules can be imported from list
|
||||
|
||||
.. versionadded:: 3.8
|
||||
"""
|
||||
for module_name in (module,) + modules:
|
||||
imported_module = try_import(module_name)
|
||||
if imported_module:
|
||||
return imported_module
|
||||
|
||||
raise ImportError('Unable to import any modules from the list %s' %
|
||||
str(modules))
|
||||
|
@ -123,3 +123,11 @@ class ImportUtilsTest(test_base.BaseTestCase):
|
||||
def test_try_import_returns_default(self):
|
||||
foo = importutils.try_import('foo.bar')
|
||||
self.assertIsNone(foo)
|
||||
|
||||
def test_import_any_none_found(self):
|
||||
self.assertRaises(ImportError, importutils.import_any,
|
||||
'foo.bar', 'foo.foo.bar')
|
||||
|
||||
def test_import_any_found(self):
|
||||
dt = importutils.import_any('foo.bar', 'datetime')
|
||||
self.assertEqual(sys.modules['datetime'], dt)
|
||||
|
Loading…
x
Reference in New Issue
Block a user