improve a Python error message

Andrei project5 at redrival.net
Fri Apr 9 09:10:47 EDT 2004


beliavsky at aol.com wrote on 8 Apr 2004 12:13:07 -0700:

> 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:

  >>> x = (1, 2
  ... ,3
  ... )
  >>> x
  (1, 2, 3)

But:

  >>> x = (1,2
  ... 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:

  >>> x = (1, 2, print 3)
    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):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.



More information about the Python-list mailing list