automatically naming a global variable
Duncan Booth
duncan at NOSPAMrcp.co.uk
Tue May 22 11:21:43 EDT 2001
chat at linuxsupreme.homeip.net (Chad Everett) wrote in
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'
>
>
Have you stopped to consider that this may be a *bad* idea, and perhaps
there is a better way to achieve whatever you want to do? In particular
creating global variables when you don't know their names in advance is
likely to conflict with the names of other globals (modules, functions
etc.) that are essential to the running of your program.
Much better would be to create a dictionary to hold your unknown variables:
mydict = {}
mydict[x] = 'some value'
That way you keep all these values with unknown names together and well
clear of everything else.
If you still want to modify globals() indirectly, you can do it:
mydict = globals()
mydict[x] = 'some value'
Also don't forget that a global variable in Python is a lot less global
than in most other languages (thank goodness).
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list