[python] Using a string variable as a variable name

Possible Duplicate:
How do I do variable variables in Python?

I have a variable with a string assigned to it and I want to define a new variable based on that string.

foo = "bar"
foo = "something else"   

# What I actually want is:

bar = "something else"

This question is related to python

The answer is


You will be much happier using a dictionary instead:

my_data = {}
foo = "hello"
my_data[foo] = "goodbye"
assert my_data["hello"] == "goodbye"

You can use setattr

name  = 'varname'
value = 'something'

setattr(self, name, value) #equivalent to: self.varname= 'something'

print (self.varname)
#will print 'something'

But, since you should inform an object to receive the new variable, this only works inside classes or modules.


You can use exec for that:

>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>>