automatically naming a global variable

s713221 at student.gu.edu.au s713221 at student.gu.edu.au
Wed May 23 13:02:03 EDT 2001


Duncan Booth wrote:
> 
> 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?
> 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'

Or an alternative is an empty class that doesn't do anything.

class Variable:
	pass

Create an instance, and whenever you want to create a named variable,
set it as an attribute of your empty.

variable = Variable

variable.var1 = 'var1'
variable.var2 = 'var2'

Because class instances use a dictionary internally to store attributes,
this is the same thing as the post above, but with a slightly different
syntax. If you want to create variables that are definable only once,
and are resistant to overwriting, 

>>> class Variable:
	def __setattr__(self,key,value):
		if self.__dict__.has_key(key):
			raise KeyError, "Key has already been defined"
		else:
			self.__dict__[key] = value

>>> variable = Variable()
>>> variable.var1 = 'var1'
>>> variable.var1 = 'variable1'
Traceback (most recent call last):
  File "<pyshell#27>", line 1, in ?
    variable.var1 = 'variable1'
  File "<pyshell#24>", line 4, in __setattr__
    raise KeyError, "Key has already been defined"
KeyError: Key has already been defined

Lots of fun. :|)

Joal Heagney/AncientHart



More information about the Python-list mailing list