Chris Rebert said:
From inside a module, I want to add a key-value pair to the module's
__dict__. Â I know I can just do:
FOO = 'bar'
at the module top-level, but I've got 'FOO' as a string and what I
really need to do is
__dict__['Foo'] = 'bar'
When I do that, I get "NameError: name '__dict__' is not defined". Â Is
it possible to do what I'm trying to do?
Yes; just modify the dict returned by the globals() built-in function
instead.
Ah, cool. Thanks.
It's usually not wise to do this and is better to use a
separate dict instead, but I'll assume you know what you're doing and
have good reasons to disregard the standard advice due to your
use-case.
Why is it unwise?
The use case is I'm importing a bunch of #define constants from a C header
file. I've got triples that I want to associate; the constant name, the
value, and a string describing it. The idea is I want to put in the
beginning of the module:
declare('XYZ_FOO', 0, "The foo property")
declare('XYZ_BAR', 1, "The bar property")
declare('XYZ_BAZ', 2, "reserved for future use")
and so on. I'm going to have hundreds of these, so ease of use, ease of
maintenance, and niceness of presentation are important.
My declare() function will not just set XYZ_FOO = 1 at module global scope,
but also insert entries in a variety of dicts so I can look up the
description string, map from a value back to the constant name, etc.
I *could* do this in a separate dict, but the notational convenience of
being able to have the original constant names globally available is pretty
important.