你想使用the importlib module http://docs.python.org/dev/library/importlib.html要处理这样的模块加载,然后只需使用getattr() http://docs.python.org/library/functions.html#getattr去上课。
例如,假设我有一个模块,somemodule.py
其中包含类Test
:
import importlib
cls = "somemodule.Test"
module_name, class_name = cls.split(".")
somemodule = importlib.import_module(module_name)
print(getattr(somemodule, class_name))
给我:
<class 'somemodule.Test'>
添加包之类的东西很简单:
cls = "test.somemodule.Test"
module_name, class_name = cls.rsplit(".", 1)
somemodule = importlib.import_module(module_name)
如果已经导入了模块/包,它不会导入它,因此您可以愉快地执行此操作,而无需跟踪加载模块:
import importlib
TWO_FACTOR_BACKENDS = (
'id.backends.AllowToBeDisabled', # Disable this to enforce Two Factor Authentication
'id.backends.TOTPBackend',
'id.backends.HOTPBackend',
#'id.backends.YubikeyBackend',
#'id.backends.OneTimePadBackend',
#'id.backends.EmailBackend',
)
backends = [getattr(importlib.import_module(mod), cls) for (mod, cls) in (backend.rsplit(".", 1) for backend in TWO_FACTOR_BACKENDS)]