Reputation: 93
I've been trying to find a way to reliably set and get values of variables with the names in strings. Anything I can find remotely close to this doesn't seem to always work. The variables can be in any module and those modules are imported.
What is the safe/correct way to get and set the values of variables?
ps - I'm as newb as they come to python
Upvotes: 9
Views: 6052
Reputation: 91049
While it would work, it is generally not advised to use variable names bearing a meaning to the program itself.
Instead, better use a dict:
mydict = {'spam': "Hello, world!"}
mydict['eggs'] = "Good-bye!"
variable_name = 'spam'
print mydict[variable_name] # ==> Hello, world!
mydict[variable_name] = "some new value"
print mydict['spam'] # ==> "some new value"
print mydict['eggs'] # ==> "Good-bye!"
(code taken from the other answer and modified)
Upvotes: 8
Reputation: 129001
spam = "Hello, world!"
variable_name = 'spam'
print globals()[variable_name] # ==> Hello, world!
globals()[variable_name] = "some new value"
print spam # ==> some new value
Upvotes: 4