[Python-ideas] with statement syntax forces ugly line breaks?

Georg Brandl g.brandl at gmx.net
Wed Sep 8 20:07:56 CEST 2010

Am 08.09.2010 18:50, schrieb Mark Summerfield:
> Hi,
> I can't see a _nice_ way of splitting a with statement over mulitple
> lines:
> class FakeContext:
>     def __init__(self, name):
>         self.name = name
>     def __enter__(self):
>         print("enter", self.name)
>     def __exit__(self, *args):
>         print("exit", self.name)
> with FakeContext("a") as a, FakeContext("b") as b:
>     pass # works fine
> with FakeContext("a") as a,
>      FakeContext("b") as b:
>     pass # synax error
> with (FakeContext("a") as a,
>       FakeContext("b") as b):
>     pass # synax error

In addition to the backslash hint already given, I'd like to explain why
this version isn't allowed: the parser couldn't distinguish between a
multi-context with and an expression in parentheses.

(In the case of import, where parens can be used around the import list,
this is different, no arbitrary expression is allowed.)


Thus spake the Lord: Thou shalt indent with four spaces. No more, no less.
Four shall be the number of spaces thou shalt indent, and the number of thy
indenting shall be four. Eight shalt thou not indent, nor either indent thou
two, excepting that thou then proceed to four. Tabs are right out.

More information about the Python-ideas mailing list