Generate variables at run time?

Peter Abel p-abel at t-online.de
Wed Jan 8 14:32:40 EST 2003


"Byron Morgan" <lazypointer at yahoo.com> wrote in message news:<VyPS9.6818$xs6.347786501 at newssvr14.news.prodigy.com>...
> Is there any way in Python to generate a new variable name based on data? I
> have tried the eval() function, but this gets rejected, if the variable
> doesn't already exist.
> 
> There has to be a way to do this, but I can't find it, probaly because I am
> just starting to learn Python.
> 
> Byron

Hi Holger,
I think this is one of the easiest things
in Python. See the following:

>>> class A:
... 	def __init__(self):
... 		self.var="This ist a programmed variable"
... 	def generate_a_new_variable(self,var_name,var_value):
... 		self.__dict__[var_name]=var_value
... 	def show_instance_attributes(self):
... 		for (name,value) in self.__dict__.items():
... 			print "%s = %s"%(name,str(value))
... 
>>> a=A()
>>> a.show_instance_attributes()
var = This ist a programmed variable
>>> print a.var
This ist a programmed variable
>>> # Now we generate a new variable
>>> a.generate_a_new_variable('NewVar',12345)
>>> print a.NewVar
12345
>>> a.show_instance_attributes()
var = This ist a programmed variable
NewVar = 12345
>>> # Now we generate the next new variable
>>> a.generate_a_new_variable('ListVar',[1,2,3,'ListItem Nr. 4'])
>>> print a.ListVar
[1, 2, 3, 'ListItem Nr. 4']
>>> a.show_instance_attributes()
var = This ist a programmed variable
ListVar = [1, 2, 3, 'ListItem Nr. 4']
NewVar = 12345
>>> # Now we generate a dictionary
>>> a.generate_a_new_variable('DictVar',{'a':1234,'b':678,999:'This ist 999'})
>>> print a.DictVar
{'a': 1234, 'b': 678, 999: 'This ist 999'}
>>> a.show_instance_attributes()
var = This ist a programmed variable
DictVar = {'a': 1234, 'b': 678, 999: 'This ist 999'}
ListVar = [1, 2, 3, 'ListItem Nr. 4']
NewVar = 12345
>>> # And so on

Hope I could help you.
Best Regards
Peter




More information about the Python-list mailing list