3

I was trying to temporarily null out a string I was passing to eval to do nothing (I didn't remove it because preserving the order was important for my hacky profile script), and was somewhat miffed that when I gave it 'pass' it dumped on me, likewise with an empty string or some equivalent do-nothing statement.

>>> eval('pass')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    pass
       ^
SyntaxError: unexpected EOF while parsing

I eventually just fed it None, but why was it a syntax error? "Unexpected EOF" perplexes me; the string is a complete statement in-and-of-itself. Does eval not tolerate keywords?

Nick T
  • 25,754
  • 12
  • 83
  • 121
  • `eval` tolerates keywords: `eval('lambda x: x')` is perfectly valid. – Phillip Cloud Aug 30 '13 at 00:43
  • 1
    Note that `exec('pass')` is valid. The way I remember the difference in `exec` and `eval` is that you use `eval` for anything that return something (including `None`.) You use `exec` for anything that does not return anything. See http://stackoverflow.com/questions/2220699/whats-the-difference-between-eval-exec-and-compile-in-python for some good examples. – korylprince Aug 30 '13 at 00:46
  • `pass` is not an expression, it's a statement -- so use `exec()` instead of `eval()` or give `eval()` an expression. `None` is an expression. – martineau Aug 30 '13 at 02:25

2 Answers2

9

Quoting from eval's documentation: "The expression argument is parsed and evaluated as a Python expression". Then, pass is a statement, not an expression.

nickie
  • 5,608
  • 2
  • 23
  • 37
0

Like nickie said, eval works with expressions, but I wanted to add that eval is good to understand along with repr as talked about here,

Understanding repr( ) function in Python

Community
  • 1
  • 1