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"
You can use exec for that:
>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>>
exec / eval is considered poor practice. I have not met a single use case where it has been helpful, and there are usually better alternatives such as dict.dict.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.
MyModule.var
execis becauselocals()doesn't support modifications.locals()doesn't support modifications because it would make the implementation more complex and slower and is never a good idea