我想执行以下操作(python3):
在模块 settings.py
中:
message = 'Hello'
在模块__main__.py
中:
from . import settings
def dict_from_module(module):
...
return d
print(dict_from_module(settings))
运行它应该产生:
{'message': 'hello'}
是否有将模块转换为字典的规范方法?
编辑
使用 vars(settings)
提供大量内部信息:
{
'__builtins__': {
...
},
'__cached__': 'xxx/__pycache__/settings.cpython-34.pyc',
'__doc__': None,
'__file__': 'xxx/settings.py',
'__loader__': <_frozen_importlib.SourceFileLoader object at 0x7f87fc192518>,
'__name__': 'xxx.settings',
'__package__': 'xxx',
'__spec__': ModuleSpec(...),
'message': 'bye'
}
我不想要/不需要。我可以过滤掉它(通过删除以 __
开头的键),但如果有可接受的方法,我想避免乱搞。
最佳答案
希望这对您有所帮助!
def dict_from_module(module):
context = {}
for setting in dir(module):
# you can write your filter here
if setting.islower() and setting.isalpha():
context[setting] = getattr(module, setting)
return context
关于python - 将模块转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35598512/