[Python-ideas] with statement syntax forces ugly line breaks?
Gregory P. Smith
greg at krypto.org
Thu Sep 9 07:05:35 CEST 2010
On Wed, Sep 8, 2010 at 10:00 AM, Nathan Schneider <nathan at cmu.edu> wrote:
> Mark,
>
> I have approached these cases by using the backslash line-continuation
> operator:
>
> with FakeContext("a") as a, \
> FakeContext("b") as b:
> pass
>
> Nathan
>
I'm in the "\ is evil" at all costs camp so I'd suggest either the nested
with statements or alternatively do this:
fc = FakeContext
with fc("a") as a, fc("b") as b:
pass
> On Wed, Sep 8, 2010 at 12:50 PM, Mark Summerfield <mark at qtrac.eu> wrote:
> > 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
> >
> > The use case where this mattered to me was this:
> >
> > with open(args.actual, encoding="utf-8") as afh,
> > open(args.expected, encoding="utf-8") as efh: actual =
> > [line.rstrip("\n\r") for line in afh.readlines()] expected =
> > [line.rstrip("\n\r") for line in efh.readlines()]
> >
> > Naturally, I could split the line in an ugly place:
> >
> > with open(args.actual, encoding="utf-8") as afh, open(args.expected,
> > encoding="utf-8") as efh:
> >
> > but it seems a shame to do so. Or am I missing something?
> >
> > I'm using Python 3.1.2.
> >
> > --
> > Mark Summerfield, Qtrac Ltd, www.qtrac.eu
> > C++, Python, Qt, PyQt - training and consultancy
> > "Rapid GUI Programming with Python and Qt" - ISBN 0132354187
> > http://www.qtrac.eu/pyqtbook.html
> > _______________________________________________
> > Python-ideas mailing list
> > Python-ideas at python.org
> > http://mail.python.org/mailman/listinfo/python-ideas
> >
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20100908/4f05d5b1/attachment.html>
More information about the Python-ideas
mailing list