automatically naming a global variable
aleaxit at yahoo.com
Tue May 22 18:05:14 CEST 2001
"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).
Somebody is sure to suggest the exec statement... I suggest
you ignore the suggestion:-).
More information about the Python-list