Using a string variable as a variable name

Python

Python Problem Overview


> 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"

Python Solutions


Solution 1 - Python

You can use exec for that:

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

Solution 2 - Python

You will be much happier using a dictionary instead:

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

Solution 3 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question9-bitsView Question on Stackoverflow
Solution 1 - PythonJack LeowView Answer on Stackoverflow
Solution 2 - PythonNed BatchelderView Answer on Stackoverflow
Solution 3 - PythonGustavo VargasView Answer on Stackoverflow