Get global variables from file as dict?

淺唱寂寞╮ 提交于 2019-12-11 06:26:42

问题


I've got a file, constants.py, that contains a bunch of global constants. Is there a way I can grab all of them as dict, for just this file?


回答1:


It should be simple:

import constants
print(constants.__dict__)



回答2:


import constants

constants_dict = {}
for constant in dir(constants):
    constants_dict[constant] = getattr(constants, constant)

I'm not sure I see the point of this though. How is writing constants_dict['MY_CONSTANT'] any better/easier/more readable than constants.MY_CONSTANT?

EDIT:

Based on the comments, I see some potential uses now.

Here's another way to write the above, depending on how compact you want it.

constants_dict = dict((c, getattr(constants, c)) for c in dir(constants))

EDIT2:

cji for the win! constants.__dict__



来源:https://stackoverflow.com/questions/3460864/get-global-variables-from-file-as-dict

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!