[Python-Dev] Multiline with statement line continuation

Allen Li cyberdupo56 at gmail.com
Tue Aug 12 01:08:00 CEST 2014


This is a problem I sometimes run into when working with a lot of files
simultaneously, where I need three or more `with` statements:

    with open('foo') as foo:
        with open('bar') as bar:
            with open('baz') as baz:
                pass

Thankfully, support for multiple items was added in 3.1:

    with open('foo') as foo, open('bar') as bar, open('baz') as baz:
        pass

However, this begs the need for a multiline form, especially when
working with three or more items:

    with open('foo') as foo, \
         open('bar') as bar, \
         open('baz') as baz, \
         open('spam') as spam \
         open('eggs') as eggs:
        pass

Currently, this works with explicit line continuation, but as all style
guides favor implicit line continuation over explicit, it would be nice
if you could do the following:

    with (open('foo') as foo,
          open('bar') as bar,
          open('baz') as baz,
          open('spam') as spam,
          open('eggs') as eggs):
        pass

Currently, this is a syntax error, since the language specification for
`with` is

    with_stmt ::=  "with" with_item ("," with_item)* ":" suite
    with_item ::=  expression ["as" target]

as opposed to something like

    with_stmt ::=  "with" with_expr ":" suite
    with_expr ::=  with_item ("," with_item)*
              |    '(' with_item ("," with_item)* ')'

This is really just a style issue, furthermore a style issue that
requires a change to the languagee grammar (probably, someone who knows
for sure please confirm), so at first I thought it wasn't worth
mentioning, but I'd like to hear what everyone else thinks.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 473 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-dev/attachments/20140811/0cd007b3/attachment.sig>


More information about the Python-Dev mailing list