automatically naming a global variable

Chad Everett chat at linuxsupreme.homeip.net
Tue May 22 12:47:23 EDT 2001


On Tue, 22 May 2001 18:05:14 +0200, Alex Martelli <aleaxit at yahoo.com> wrote:
>"Chad Everett" <chat at linuxsupreme.homeip.net> wrote in message
>news:slrn9gkvqk.5j4.chat at linuxsupreme.homeip.net...
>>
>> If I have a string variable defined, how can I create a global
>> variable with the same name as the string?
>>
>> For example:
>>
>> >>> x = "variable_name'
>>
>> Now I want to be able to use x to create a global variable whose
>> name is 'variable_name'
>
>setattr(sys.modules[__name__], x, 23) should work (if you
>have imported sys, of course).  A global variable is no more
>and no less than an attribute on your current module object,
>after all.  sys.modules[__name__] is one way to say "the
>module this code is in" (there are other ways).
>
>But this is hardly ever appropriate.  Generally, on digging
>a bit deeper, it turns out that whatever problem you think
>you're solving is better solved otherwise -- generally by
>more explicitly using a dictionary, as it happens (objects
>taking arbitrarily-named attributes, such as modules for
>example, implicitly use dictionaries, too).
>

I have sets that are described by a list of attributes and 
properties that are implemented using python dictionaries.
One of a set's attributes is its name.  I need to provide
the user with a mechanism for referring to a dictionary that
represents a set, by using the set's name.  The user does
not want to have to reference the set via something like:

	sets['set_name']

They need to have a variable that references to the dictionary
for the set by simply using set_name.

I need to be able do this:

set_name = sets['set_name'], so that:

>>> set_name

and

>>> sets['set_name']

reference exactly the same thing.





More information about the Python-list mailing list