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
The globals() and locals() functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by eval() or execfile().
Basically, eval is used to evaluate a single dynamically generated Python expression, and exec is used to execute dynamically generated Python code only for its side effects.
literal_eval may be a safer alternative. literal_eval() would only evaluate literals, not algebraic expressions.
In the end, it is possible to safely evaluate untrusted Python expressions, for some definition of “safe” that turns out not to be terribly useful in real life. It's fine if you're just playing around, and it's fine if you only ever pass it trusted input. But anything else is just asking for trouble.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With