What does Python's eval() do?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Unforgiving Himalayas Looping
--
Chapters
00:00 Question
00:29 Accepted answer (Score 307)
00:48 Answer 2 (Score 177)
01:28 Answer 3 (Score 72)
03:50 Answer 4 (Score 29)
04:32 Thank you
--
Full question
https://stackoverflow.com/questions/9383...
Answer 2 links:
[in the documentation]: https://docs.python.org/3/library/functi...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #eval
#avk47
ACCEPTED ANSWER
Score 312
The eval function lets a Python program run Python code within itself.
eval example (interactive shell):
>>> x = 1
>>> eval('x + 1')
2
>>> eval('x')
1
ANSWER 2
Score 182
eval() interprets a string as code. The reason why so many people have warned you about using this is because a user can use this as an option to run code on the computer. If you have eval(input()) and os imported, a person could type into input() os.system('rm -R *') which would delete all your files in your home directory. (Assuming you have a unix system). Using eval() is a security hole. If you need to convert strings to other formats, try to use things that do that, like int().
ANSWER 3
Score 29
In Python 2.x input(...) is equivalent to eval(raw_input(...)), in Python 3.x raw_input was renamed input, which I suspect lead to your confusion (you were probably looking at the documentation for input in Python 2.x). Additionally, eval(input(...)) would work fine in Python 3.x, but would raise a TypeError in Python 2.
In this case eval is used to coerce the string returned from input into an expression and interpreted. Generally this is considered bad practice.
ANSWER 4
Score 7
eval(), as the name suggests, evaluates the passed argument.
raw_input() is now input() in Python 3.x versions. So the most commonly found example for the use of eval() is its use to provide the functionality that input() provided in 2.x version of Python.
raw_input returned the user-entered data as a string, while input evaluated the value of data entered and returned it.
eval(input("bla bla")) thus replicates the functionality of input() in 2.x, i.e., of evaluating the user-entered data.
In short: eval() evaluates the arguments passed to it and hence eval('1 + 1') returned 2.