[Python-Dev] Multiline with statement line continuation

Nick Coghlan ncoghlan at gmail.com
Tue Aug 12 02:28:14 CEST 2014


On 12 Aug 2014 09:09, "Allen Li" <cyberdupo56 at gmail.com> wrote:
>
> 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

I generally see this kind of construct as a sign that refactoring is
needed. For example, contextlib.ExitStack offers a number of ways to manage
multiple context managers dynamically rather than statically.

Regards,
Nick.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20140812/a2e6f24d/attachment.html>


More information about the Python-Dev mailing list