A utility function to import a class from a module given syntax such as used by nose and setuptools entry points.
This commit is contained in:
parent
ce03037f5d
commit
01b2b8c689
19
devstack/importer.py
Normal file
19
devstack/importer.py
Normal file
@ -0,0 +1,19 @@
|
||||
|
||||
|
||||
def import_entry_point(fullname):
|
||||
"""Given a name import the class and return it.
|
||||
|
||||
The name should be in dotted.path:ClassName syntax.
|
||||
"""
|
||||
if ':' not in fullname:
|
||||
raise ValueError('Invalid entry point specifier %r' % fullname)
|
||||
module_name, ignore, classname = fullname.partition(':')
|
||||
try:
|
||||
module = __import__(module_name)
|
||||
for submodule in module_name.split('.')[1:]:
|
||||
module = getattr(module, submodule)
|
||||
cls = getattr(module, classname)
|
||||
except (ImportError, AttributeError) as err:
|
||||
raise RuntimeError('Could not load entry point %s: %s' %
|
||||
(fullname, err))
|
||||
return cls
|
13
tests/test_importer.py
Normal file
13
tests/test_importer.py
Normal file
@ -0,0 +1,13 @@
|
||||
|
||||
from devstack import importer
|
||||
from devstack import distro
|
||||
|
||||
|
||||
def test_function():
|
||||
f = importer.import_entry_point('devstack.importer:import_entry_point')
|
||||
assert f == importer.import_entry_point
|
||||
|
||||
|
||||
def test_class():
|
||||
c = importer.import_entry_point('devstack.distro:Distro')
|
||||
assert c == distro.Distro
|
Loading…
Reference in New Issue
Block a user