Line-continuation "Anti-Idiom" and with statement

MRAB python at mrabarnett.plus.com
Mon Nov 23 21:17:19 CET 2009


Neil Cerutti wrote:
 > I installed Python 3.1 today, and I've been porting my small
 > library of programs to the new system.
 >
 > I happened to read the interesting "Idioms and Anti-Idioms"
 > HOWTO, and saw the '\' continuation character labeled an
 > anti-idiom. I already generally avoided it, so I just nodded.
 >
 > Unfortunately, the new "nested" with statement (which I also read
 > about today) forces me into this anti-idiom. When replacing an
 > appearance of contextlib.nested with the 3K with statement, I
 > ended up with an unexpected syntax error.
 >
 > with (open(roster_path, 'r') as roster_file,
 >       open(disb_path, 'w') as out_file,
 >       open(report_path, 'w') as report_file):
 >
 > The result was:
 >
 >   File "C:\project\codxml.py", line 184
 >     with (open(roster_path, 'r') as roster_file,
 >                                   ^
 > SyntaxError: invalid syntax
 >
 > Unless I'm missing something, I have to subject my code to a bit
 > of contintuation:
 >
 > with open(roster_path, 'r') as roster_file,\
 >      open(disb_path, 'w') as out_file,\
 >      open(report_path, 'w') as report_file:
 >
 > I was thinking about submitting a enhancement request to the
 > HOWTO, explaining that continuation my be required in this
 > context. Am I missing anything obvious?
 >
The relevant syntax is:

     with_stmt ::= "with" with_item ("," with_item)* ":" suite

     with_item ::= expression ["as" target]

Parentheses only work around an expression or when they are expected by
the syntax, eg in function calls.

In this case it sees the '(' and thinks that it's the start of a
parenthesised expression. It parses the expression, then sees 'as',
hence a SyntaxError. I suppose it could've complained about a missing
')' instead.

I wonder whether an end-of-line could be ignored after a comma in a
'with' statement, and, for consistency, in any similar cases.



More information about the Python-list mailing list