user2424005
user2424005

Reputation: 93

Alternatives to exec/eval?

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

Answers (2)

glglgl
glglgl

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

icktoofay
icktoofay

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

Related Questions