Line-continuation "Anti-Idiom" and with statement

Neil Cerutti neilc at norwich.edu
Tue Nov 24 09:20:59 EST 2009


On 2009-11-23, Terry Reedy <tjreedy at udel.edu> wrote:
> Neil Cerutti wrote:
>> 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
>
> Right. The first open paren is illegal.
>
> I believe that '\ \n' would always be harmless or a SyntexError
> outside of expressons. I believe 'subtly wrong' only applies
> within expressions. 
>
> So I would not call \ continuation an anti-pattern outside
> expressions. So you might suggest that the whole entry specify
> expression context to begin with. To me, your example shows why
> blanket condemnation is wrong.
>
> The HOWTOs are not scripture.

I like your suggestion. Changing the title of the anti-idiom to
"Using Backslash to Continue Expressions" seems like a good fix.
I submitted it as issue 7391.

I've done a search of the PEP's, Python-Dev, and Python-Ideas,
but I couldn't find much official discussion. The change was made
because contextlib.nested was not semantically equivalent to
actual nested with statments.

GvR noted in Python Ideas that he liked the idea of making the
new syntax parallel to the import statement sytax variant:

"import" module  ["as" name] ( ", " ["as" name] )*

So that's where the 'multi-with' statement found its model.

-- 
Neil Cerutti



More information about the Python-list mailing list