将模块转换为字典

dan*_*ast 5 python dictionary namespaces module python-3.x

我想执行以下操作(python3):

在模块中settings.py

message = 'Hello'
Run Code Online (Sandbox Code Playgroud)

在模块中__main__.py

from . import settings


def dict_from_module(module):
    ...
    return d

print(dict_from_module(settings))
Run Code Online (Sandbox Code Playgroud)

运行它应该产生:

{'message': 'hello'}
Run Code Online (Sandbox Code Playgroud)

是否有将模块转换为字典的规范方法?

编辑

使用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'
}
Run Code Online (Sandbox Code Playgroud)

我不想要/不需要的。我可以将其过滤掉(通过删除以开头的键__),但是如果可以接受的话,我想避免乱搞。

小智 5

希望这可以帮助!

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
Run Code Online (Sandbox Code Playgroud)

  • 我的方式: `module_to_dict = lambda module: {k: getattr(module, k) for k in dir(module) if not k.startswith('_')}` (2认同)