PProteus
PProteus

Reputation: 599

Why does the Python interpreter show syntax errors on the following line?

I've been helping a new Python user with some code, and he asked me why the python interpreter shows some syntax errors on the line after the actual error. Consider the following code:

x = [1, 2, 3
print x

A syntax error will be shown for the line with print x, although the error is really on the previous line.

This can be very confusing (and time wasting) the first time you run into it, it is a very common issue (search for "python syntax error" on your favourite search engine), and it seems like it wouldn't be difficult to rectify... why hasn't it been fixed? Is there some benefit to the present approach?

Upvotes: 1

Views: 427

Answers (2)

Cristian Lupascu
Cristian Lupascu

Reputation: 40536

It is valid Python syntax to split a list across multiple lines, like so:

x = [1, 2, 3
, 4, 5, 6]
print x

So, the interpreter starts reading the print... line expecting a valid continuation of the list, which it obviously cannot find.

Also, I don't find this terribly misleading. I think it's pretty easy to figure out why you get the error.

Upvotes: 7

Scimonster
Scimonster

Reputation: 33409

x = [1, 2, 3
]
print x

Valid syntax! Because this is possible, the error is actually on line 2 when the list doesn't continue or end.

Upvotes: 2

Related Questions