2

As a beginner python programmer, I am hoping this is some stupid error (or lack of understanding) that has an simple solution:

/tmp> python3 -c 'with open("t","r") as f: for l in f: print(l)'
  File "<string>", line 1
    with open("t","r") as f: for l in f: print(l)
                               ^
SyntaxError: invalid syntax

I can embed a newline in the oneline, but trying to understand why the above does not work

/tmp> python3 -c $'with open("t","r") as f:\n for l in f: print(l)'
Hi there
Miserable Variable
  • 28,432
  • 15
  • 72
  • 133

1 Answers1

1

Looking at the Full grammar specification, the only statements you're allowed to put immediately after a with statement on the same line, are statements in the simple_stmt class.

Relevant parts of the grammar:

with_stmt: 'with' with_item (',' with_item)*  ':' suite
suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT
simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt |
             import_stmt | global_stmt | nonlocal_stmt | assert_stmt)
flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt

In plainer language, these statements appear to be:

  • Expression statements
  • del
  • pass
  • break
  • continue
  • return
  • raise
  • yield
  • import
  • global
  • nonlocal
  • assert

for is not part of this list, so it is not allowed to come immediately after a with with no intervening newline.

Kevin
  • 74,910
  • 12
  • 133
  • 166