I’m writing a Python parser to learn Flex and Bison, and I’m trying to find out why only the first of these programs is valid Python.
a.py:
\
# This is valid Python
produces no error.
b.py:
\
# This is not valid Python
produces this error:
File "b.py", line 1
\
^
IndentationError: unexpected indent
and c.py:
if True:
pass
\
# This is not valid Python
produces this error:
File "c.py", line 4
# This is not valid Python
^
SyntaxError: invalid syntax
I’m using Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 (Ubuntu 10.04); However, testing on ideone.com suggests the behavior is the same on Python 3.
See also: How can I do a line break (line continuation) in Python (split up a long line of source code)?
It’s an implementation detail.
Here’s how a few different implementations respond to your code:
My reading of the Exlplicit Line Joining section of the Python Language Reference is that all three examples could be treated as valid:
If CPython were changed to accept all three examples as valid I doubt it would be noticed by its users, change the character of the language, or break any code.