Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 629
user2424005 Avatar asked May 27 '13 07:05

user2424005


People also ask

What can I use instead of exec in 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().

What is the difference between exec and eval?

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.

What can I use instead of eval in Python?

literal_eval may be a safer alternative. literal_eval() would only evaluate literals, not algebraic expressions.

Is Python eval secure?

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.


1 Answers

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)

like image 81
glglgl Avatar answered Oct 12 '22 23:10

glglgl