Get global variables from file as dict?

2019-07-29 07:37发布

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?

2条回答
爷、活的狠高调
2楼-- · 2019-07-29 08:07
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__

查看更多
一纸荒年 Trace。
3楼-- · 2019-07-29 08:13

It should be simple:

import constants
print(constants.__dict__)
查看更多
登录 后发表回答