variable variables?

Sean Blakey sblakey at freei.com
Wed Aug 9 20:49:03 EDT 2000


On Thu, Aug 10, 2000 at 12:38:20AM +0000, Matthew R. MacIntyre wrote:
> 
> Hello all,
> 
> Does python support "variable variables"?  I've been trying something like
> this, but to no avail:
> 
> var1 = "foo"
> varname = "var1"
> 
> then i want to do something like:
> {varname} = bar
> print var1
> => bar
> 
> Is this do-able?
> 

Yes, through exec/eval
var1 = 'foo1'
varname = 'var1'
exec(varname + '="bar"')

> More specifically, i'm trying to set instance variables in a class using
> an argument containing a dictionary in the constructor .... something like
> this:
> 
> class TestClass:
> 	def __init__(self,dict):
>            for x in dict.keys()
>              self._{x} = dict[x]
> 
> 	def show(self):
> 		print self._var1
> 		print self._var2
> 
> args = { 'var1' : "value1", 'var2' : "value2" }
> test = TestClass(args)
> test.show()
> 
> I want the test.show() to print :
> 
> value1
> value2
> 
> but I'm having no such luck on the various variations of this theme that
> I've been dreaming up.
> 
> Is this even possible to do?  Is it an outrageous thing to try to do?  If
> so, what is a better way to do it?
> 
> Thanks,
> 
> -matt
> 
> -- 
> http://www.python.org/mailman/listinfo/python-list

You should really look at the built in getattr/setattr functions.  For
example:
class TestClass:
    def __init__(self, dict):
	for key, value in dict.items():
	    setattr(self, '_' + key, value)

    def show(self):
	print self._var1
	print self._var2
	
args = {'var1': 'value1', 'var2': 'value2'}
test = TestClass(args)
test.show()

-- 
Sean Blakey, sblakey at freei.com
Software Developer, FreeInternet.com
(253)796-6500x1025
"No problem is so formidable that you can't walk away from it."
 -- C. Schulz




More information about the Python-list mailing list