Question

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?

Was it helpful?

Solution

It should be simple:

import constants
print(constants.__dict__)

OTHER TIPS

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__

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top