Get global variables from file as dict?

2019-07-29 07:50发布

问题:

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__