The problem isn't with the import statement specifically. It’s that you have anything before a control flow statement. This won't work, either:
dan@dan:~> python -c 'a = "1234" ; if True: print "hi"'
File "<string>", line 1
a = "1234" ; if True: print "hi"
^
SyntaxError: invalid syntax
According to the Python reference (7. Compound statements), ';' can only be used to combine "simple statements" together. In this case you're combining the simple statement import re
, with if True:
. if True
isn't a simple statement, because it’s introducing flow control, and is therefore a compound statement. At least that's how I interpret the documentation.
Here's the full text from the Python reference:
Compound statements consist of one or more ‘clauses.’ A clause
consists of a header and a ‘suite.’ The clause headers of a particular
compound statement are all at the same indentation level. Each clause
header begins with a uniquely identifying keyword and ends with a
colon. A suite is a group of statements controlled by a clause. A
suite can be one or more semicolon-separated simple statements on the
same line as the header, following the header’s colon, or it can be
one or more indented statements on subsequent lines
compound_stmt ::= if_stmt
| while_stmt
| for_stmt
| try_stmt
| with_stmt
| funcdef
| classdef
| decorated
suite ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
statement ::= stmt_list NEWLINE | compound_stmt
stmt_list ::= simple_stmt (";" simple_stmt)* [";"]