improve a Python error message

B

beliavsky

The Python code

x = (1,2
print x

gives an error message

File "err.py", line 2
print x
^
SyntaxError: invalid syntax

The real error is on line 1, but I guess the error is attributed to
line 2 because the code would be legal if the 2nd line were (for
example) a closing parenthesis. I wonder if the error message Python
produces could be improved. It is technically correct but could
confuse a beginner. Perhaps the message could be

SyntaxError: invalid syntax (missing closing parenthesis on previous
line?)
 
A

Andrei

x = (1,2
print x

gives an error message

File "err.py", line 2
print x
^
SyntaxError: invalid syntax

The real error is on line 1, but I guess the error is attributed to
line 2 because the code would be legal if the 2nd line were (for
example) a closing parenthesis. I wonder if the error message Python
produces could be improved. It is technically correct but could
confuse a beginner. Perhaps the message could be

SyntaxError: invalid syntax (missing closing parenthesis on previous
line?)

I think that generally speaking you're right and this type of error does
tend to come from forgetting to close parens. But Python doesn't know if
you forgot to close the paren or forgot a comma inside a tuple. E.g. it's
legal to not close a tuple on the same line where you begin it:
... ,3
... ) (1, 2, 3)

But:
... 3)
File "<input>", line 2
3)
^
SyntaxError: invalid syntax

In this case I didn't forget the parenthesis, I forgot the comma.

It's also illegal to put a print inside the tuple, regardless of comma and
parens:
File "<input>", line 1
x = (1, 2, print 3)
^
SyntaxError: invalid syntax

Your example is a mix of all three possible errors: you might have
forgotten the paren, you might have forgotten a comma and you might have
accidentally put a print inside a tuple. Python can't really know what you
meant to write there.
Imagine you have a variable called Print which you wanted to put inside a
tuple, but mistyped it as "print". Python tells you to close your
parentheses on line 1, but the mistake is really in line 2, where you
should have put a comma, uppercased 'print' and closed the parens.

--
Yours,

Andrei

=====
Real contact info (decode with rot13):
(e-mail address removed). Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,181
Messages
2,570,970
Members
47,537
Latest member
BellCorone

Latest Threads

Top