可能是一个简单的问题!我需要遍历从设置文件传递的类列表(作为字符串)。这些类列出如下:
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',
)
我现在需要在每个类上调用authenticate()
函数(当然除非被注释掉)。我很乐意在列表中进行迭代,我只需要知道如何将字符串转换为foreach循环中的Class对象,以便我可以在其上调用authenticate
方法。有一个简单的方法吗?
答案 0 :(得分:38)
您希望使用the importlib
module来处理这样的模块加载,然后只需使用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)]