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?
views:
45answers:
2
+2
A:
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__
tgray
2010-08-11 17:05:43
One thing I can think of is using computed value as a key - but then there are `getattr` and `setattr` functions.
cji
2010-08-11 17:10:54
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
2010-08-11 17:14:02
I'm passing the constants off to my template... the `constants_dict` part will drop off, and I can use my constants directly.
Mark
2010-08-11 17:14:15
@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
2010-08-11 18:12:31