[Python-ideas] Allow parentheses to be used with "with" block

Steven D'Aprano steve at pearwood.info
Mon Feb 16 18:19:58 CET 2015


On Mon, Feb 16, 2015 at 02:13:03PM +0000, Paul Moore wrote:
> On 16 February 2015 at 13:47, Chris Angelico <rosuav at gmail.com> wrote:
> > That said, I'm not sure how this would be implemented, as I don't know
> > enough about the grammar. I can explain it to a human no trouble ("you
> > can continue an expression onto a new line by simply ending with an
> > operator and indenting the next line"), but it might be hard to
> > explain to a computer. For one thing, this version of the proposal
> > requires that indentation matter to the parsing of an expression,
> > which currently it doesn't - you can open a bracket, then put the rest
> > of the expression flush left, if you want to.
> 
> It seems to me that we're talking here about replacing a slightly ugly
> but explicit and already existing construct (backslash continuation)

Ugly and fragile. Accidentally adding invisible whitespace after the \ 
breaks it.

(I've never quite understood why the parser doesn't just accept 
"backslash followed by zero or more tabs/spaces" instead of just 
backslash. But that's another question.)


> with something that seems to be pretty difficult to agree on and/or
> explain (depending on the proposal).
> 
> It might be worth remembering that the original post was asking for an
> alternative to backslashes *because the Google guidelines prohibit
> them*. Surely the obvious answer is to change the Google guidelines?

Allowing parens in with clauses has been requested many times, because 
none of the existing ways of dealing with long with statements are 
satisfactory. It's not just a "foolish consistency" (quoting PEP 8) with 
a style guide, but that using backslashes is *ugly and fragile* and 
other solutions are uglier:

with open("/tmp/a", "w") as a, open(
          "/tmp/b", "w") as b, open(
          "/tmp/c", "w") as c:
    pass


None of the existing solutions is really satisfactory, so it is not 
surprising that people keep asking to be able to write:

with (open("/tmp/a", "w") as a, 
      open("/tmp/b", "w") as b, 
      open("/tmp/c", "w") as c
      ):
    pass


Nothing to do with Google's style guide at all.



-- 
Steve


More information about the Python-ideas mailing list