Search code examples
pythonpython-3.xmultilinewith-statement

Python multi-line with statement


What is a clean way to create a multi-line with in python? I want to open up several files inside a single with, but it's far enough to the right that I want it on multiple lines. Like this:

class Dummy:
    def __enter__(self): pass
    def __exit__(self, type, value, traceback): pass

with Dummy() as a, Dummy() as b,
     Dummy() as c:
    pass

Unfortunately, that is a SyntaxError. So I tried this:

with (Dummy() as a, Dummy() as b,
      Dummy() as c):
    pass

Also a syntax error. However, this worked:

with Dummy() as a, Dummy() as b,\
     Dummy() as c:
    pass

But what if I wanted to place a comment? This does not work:

with Dummy() as a, Dummy() as b,\
     # my comment explaining why I wanted Dummy() as c\
     Dummy() as c:
    pass

Nor does any obvious variation on the placement of the \s.

Is there a clean way to create a multi-line with statement that allows comments inside it?


Solution

  • Python 3.9+ only:

    with (
        Dummy() as a,
        Dummy() as b,
        # my comment explaining why I wanted Dummy() as c
        Dummy() as c,
    ):
        pass
    

    Python ≤ 3.8:

    with \
        Dummy() as a, \
        Dummy() as b, \
        Dummy() as c:
        pass
    

    Unfortunately, comments are not possible with this syntax.