[Python-ideas] with-statement syntactic quirk
ncoghlan at gmail.com
Wed Oct 31 12:55:54 CET 2012
On Wed, Oct 31, 2012 at 8:38 PM, Barry Warsaw <barry at python.org> wrote:
> with-statements have a syntactic quirk, which I think would be useful to fix.
> This is true in Python 2.7 through 3.3, but it's likely not fixable until 3.4,
> unless of course it's a bug <wink>.
>>>> with open('/etc/passwd') as p1, open('/etc/passwd') as p2: pass
> Not legal:
>>>> with (open('/etc/passwd') as p1, open('/etc/passwd') as p2): pass
> Why is this useful? If you need to wrap this onto multiple lines, say to fit
> it within line length limits. IWBNI you could write it like this:
> with (open('/etc/passwd') as p1,
> open('/etc/passwd') as p2):
> This seems analogous to using parens to wrap long if-statements, but maybe
> there's some subtle corner of the grammar that makes this problematic (like
> 'with' treating the whole thing as a single context manager).
It's not an especially subtle corner of the grammar, it's
tuples-as-context-managers (i.e. the case with no as clauses) that
with (cmA, cmB):
This is: a) useless (because tuples aren't context managers); but also
b) legal syntax (it blows up at runtime, complaining about a missing
__enter__ or __exit__ method rather than throwing SyntaxError at
Adding support for line continuation with parentheses to import
statements was easier, because they don't accept arbitrary
subexpressions, so there was no confusion with tuples.
I do think it makes sense to change the semantics of this, but I ain't
volunteering to figure out the necessary Grammar changes :P
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
More information about the Python-ideas