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

Mark Summerfield mark at qtrac.eu
Thu Sep 9 07:49:51 CEST 2010


Hi Nathan,

On Wed, 8 Sep 2010 13:00:25 -0400
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

Yes, of course, and that's the way I've done it. But it seems a pity to
do it this way when the documentation explicitly discourages the use of
the backslash for line continuation:
http://docs.python.org/py3k/howto/doanddont.html
(look at the very last item)


> 
> Nathan
> 
> 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
> >



-- 
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
    C++, Python, Qt, PyQt - training and consultancy
        "Programming in Python 3" - ISBN 0321680561
            http://www.qtrac.eu/py3book.html



More information about the Python-ideas mailing list