[Python-ideas] with statement syntax forces ugly line breaks? (original) (raw)

M.-A. Lemburg mal at egenix.com
Thu Sep 9 15:32:15 CEST 2010


Mark Summerfield 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?

Why do you need to put everything on one line ?

afh = open(args.actual, encoding="utf-8") efh = open(args.expected, encoding="utf-8")

with afh, efh: ...

In the context of files, the only purpose of the with statement is to close them when leaving the block.

a = open('/etc/passwd') b = open('/etc/group') with a,b: print a.readline(), b.readline() ... at:x:25:25:Batch jobs daemon:/var/spool/atjobs:/bin/bash at:!:25:

a <closed file '/etc/passwd', mode 'r' at 0x7f0093e62390> b <closed file '/etc/group', mode 'r' at 0x7f0093e62420>

-- Marc-Andre Lemburg eGenix.com

Professional Python Services directly from the Source (#1, Sep 09 2010)

Python/Zope Consulting and Support ... http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/


2010-08-19: Released mxODBC 3.1.0 http://python.egenix.com/ 2010-09-15: DZUG Tagung, Dresden, Germany 6 days to go

::: Try our new mxODBC.Connect Python Database Interface for free ! ::::

eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/



More information about the Python-ideas mailing list