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?
Asked
Active
Viewed 747 times
2 Answers
5
It should be simple:
import constants
print(constants.__dict__)

cji
- 6,635
- 2
- 20
- 16
-
Wow, this is way simpler than my answer. – tgray Aug 11 '10 at 17:26
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__
-
One thing I can think of is using computed value as a key - but then there are `getattr` and `setattr` functions. – cji Aug 11 '10 at 17:10
-
Well, I can answer that for my current project (though my problem was functions, not variables): we had to reference the variable (function, in my case) across three socket connections, a USB connection, and a radio signal (that's the full path from function call to function execution). The destination needed a dictionary of string:function pairings to know what function to call, when only given a function name and the parameter values to use. More specifically, we paired the string:function, and then paired byte:string, which let us pair byte:function (severely cutting down on packet size). – Brian S Aug 11 '10 at 17:14
-
I'm passing the constants off to my template... the `constants_dict` part will drop off, and I can use my constants directly. – mpen Aug 11 '10 at 17:14
-
@myself - rationale given in comments above made me rethink this problem and then easiest solution appeared at once - I used `__dict__` attribute quite a few times to avoid writing `object.something` (instead of just `something`) in Django templates - it's not elegant, but it works. In my case I updated `context` with `__dict__` of some object instance - but it is applicable to modules as well. It will fail, however, if you have class with `__slots__` defined - and probably when you try to query some package (`__init__.py` without `__all__`). – cji Aug 11 '10 at 18:12