1

Why this code gives me a syntax error:

eval(1485*'not ' + '1')

Obviously the syntax is correct. Below 1485 works fine. And with 1496 and above I get a memory error. I think it should rise a MemoryError instead of SyntaxError.

17
  • 2
    eval("1485*'not ' + '1'") runs fine on my machine, but I guess I should ask: what are you trying to do? Commented Oct 16, 2014 at 21:22
  • 1
    @RafaelBarros thats because in your case it just returns a string. Note there are no double quotes around. Commented Oct 16, 2014 at 21:24
  • 3
    @RafaelBarros and user1269942, he's generating a string with 14895 "not"s in front of a '1', then evaling it. It's valid as written, just... nonsensical. Commented Oct 16, 2014 at 21:25
  • 1
    Look at the first line of output in the traceback. The cause is clearly stated: s_push: parser stack overflow. It looks like you overwhelmed the parser (at least, that is the result on my Windows 7 machine running Python 2.7.8). Commented Oct 16, 2014 at 21:26
  • 1
    @RafaelBarros That just evals as a really long string, not the same thing. Commented Oct 16, 2014 at 21:33

1 Answer 1

5

The parser has limits, and you are hitting them. See http://bugs.python.org/issue1881 for a discussion, but you managed to add enough not operators in there to run out of parser stack space.

You can hit the same limit by nesting lists, see http://bugs.python.org/issue215555:

>>> eval(100 * '[' + 100 * ']')
s_push: parser stack overflow
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
MemoryError

Quoting that latter report:

There is a limit that is based on the C stack, because the parser is recursive descent.

Providing code that hits that limit is considered a syntax error too; e.g. 1485 not operators in a row is insane and cannot possibly be considered valid Python. :-)

The reason you are getting a EOF error rather than a MemoryError for certain lengths is simply that the tokenizer manages to get to the end of the line (and signals an EOF) for those lengths, and then the parser stack overflows, rather than that the parser stack overflowed before the tokenizer had seen the end of the line.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, but this doesn't explain why it's SyntaxError for the values from 1485 to 1496, and MemoryError otherwise.
@georg: the memory error is hit in the parser too, again due to running out of stack space, but more so.
@georg: dug a little more; the parser stack overflow is always a MemoryError, but if the tokenizer has seen the end of the line already as it feeds tokens to the parser, the memory error is replaced by the syntax error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.