0

what does x=eval(input("hello")) mean, doesn't it suppose to be instead of eval() something like int? I thought of x as a variable that belong to some class that determine its type, does eval include all known classes like int float complex...?

user2864740
  • 60,010
  • 15
  • 145
  • 220
user7777777
  • 219
  • 2
  • 10
  • 1
    eval, like the documentation says, evaluates the parameter as if it were python code. It can be anything that is a valid python expression. It can be a function. – njzk2 Feb 10 '14 at 20:46
  • Search protip: "python eval" - first hit was http://docs.python.org/2/library/functions.html#eval which says "The expression argument is parsed and evaluated as a Python expression.." – user2864740 Feb 10 '14 at 20:47
  • 2
    (Also, you're either damn lucky or chose an interesting handle..) – user2864740 Feb 10 '14 at 20:50

2 Answers2

4

eval, like the documentation says, evaluates the parameter as if it were python code. It can be anything that is a valid python expression. It can be a function, a class, a value, a loop, something malicious...

Rule of thumb: Unless there is no other choice, don't use it. If there is no other choice, don't use it anyway.

njzk2
  • 38,969
  • 7
  • 69
  • 107
0

eval() will interpret the content typed by the user during the input(). So if the user type x+1 with x equals to 1 in locals, it will output 2 (see below).
An extract from the documentation:

The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace.

>>> x = 1
>>> print eval('x+1')
2

It can be dangerous, since the user can type whatever he wants, like... some Unix command. Don't use it, unless you know what you are doing (even so, it leads to serious security flaws).

Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
  • `eval()` evaluates expressions. `eval("a = 1")` is an error because an assignment is not an expression. – kindall Feb 10 '14 at 20:56