1

I was just running some code I had written for a learning exercise and suddenly ran into an error "SyntaxError: invalid syntax", from eval("alist += [foo]"). To try and understand I just made a simple module:

a = 5
eval("a += 1")
print(a)

and indeed it gives the same error, even when I just ran the first 2 lines directly into the Python console. Now I've only been doing Python a few days so I'm no expert but I'm 99% sure this should just work. a+=1 works. exec("a+=1") works. But eval("a+=1") does not, nor does eval("a-=1").

Am I doing something wrong? Is eval() not supposed to have this += function? Are others able to do this, and it's some issue with my own Python? Do I have some really strange setting on?

Celeo
  • 5,583
  • 8
  • 39
  • 41
  • ["The *expression* argument is parsed and evaluated as a Python expression"](https://docs.python.org/3/library/functions.html#eval) – melpomene Jul 06 '16 at 00:05
  • 2
    http://stackoverflow.com/questions/2220699/whats-the-difference-between-eval-exec-and-compile-in-python – Celeo Jul 06 '16 at 00:06
  • Thanks for the link Celeo, but there is so much information there I find it almost impossible to find the explicit answer to my question. – Rainbow-Anthony Lilico Jul 06 '16 at 00:47

1 Answers1

1

The first argument to eval() must be either a code object or an expression. Assignment in Python is a statement.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • Ah now that's the clarification I needed - the difference between a statement and an expression, and which eval() requires. I guess it was kinda a silly question. Clearly I wanted exec(). – Rainbow-Anthony Lilico Jul 06 '16 at 00:44