Confusing SyntaxError while entering non-indented code in interactive interpreter on continuation line.
colin.d.howell at gmail.com
Sun Apr 25 22:31:05 CEST 2010
[I originally sent this to python-help; the volunteer who responded
thought it was OK to repost it here.]
I'm sure this has been discussed somewhere before, but I can't find it
in the Python issue tracker. The following behavior from the
interactive interpreter is rather confusing. (I've seen this behavior
both under Python 2.6.5 on 32-bit Windows XP, installed from the
standard Windows binary installer available from python.org, and under
Python 2.4.3 on a Fedora Core 4 32-bit x86 Linux system.)
The following do-nothing code is valid Python:
A script file containing it will execute without error when passed to
the Python interpreter from the command line, or when run from an IDLE
edit window using the Run Module command (F5) key.
However, if the interpreter is run in interactive mode from the
command line, and I attempt to enter the same code from the
interactive prompt as follows, I get a SyntaxError at the outer "pass"
>>> if True:
File "<stdin>", line 3
SyntaxError: invalid syntax
The inner "pass" statement can be indented using spaces or with the
Tab key; it doesn't matter. The problem is that I entered the outer
"pass" statement on the second continuation line, rather than simply
hitting return and waiting for a new primary prompt. But since the
second continuation line is not indented unless you enter the
indentation yourself, this is actually an easy mistake to make. One
might think the parser will recognize that the inner block's
indentation has been removed on the new line and that the line
therefore represents a new statement.
The same thing can happen in IDLE, except that IDLE automatically
indents the continuation line and doesn't print a secondary prompt.
But if you delete IDLE's indentation on the next continuation line and
enter a new statement, you get the same SyntaxError as described
What led me to this behavior? Example 6.1 on the following page from
Dive Into Python:
In this case, the code is a try-except statement, followed by a print.
Note that the print is entered on a continuation line, which led me to
carelessly try the same thing and then puzzle about it for quite a
while before it finally hit me what I had been doing.
I know that Dive Into Python is quite old and there have been many
improvements in the language since, but I still think this gotcha
needs to be looked at, at least to add a warning about it in the FAQ
or tutorial, or to make the nature of the syntax error more obvious.
More information about the Python-list