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:
Doug Hellmann 2012-03-14 16:50:46 -04:00
parent ce03037f5d
commit 01b2b8c689
2 changed files with 32 additions and 0 deletions

19
devstack/importer.py Normal file
View 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
View 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