Python multi-line with statement Python multi-line with statement python python

Python multi-line with statement


Given that you've tagged this Python 3, if you need to intersperse comments with your context managers, I would use a contextlib.ExitStack:

from contextlib import ExitStackwith ExitStack() as stack:    a = stack.enter_context(Dummy()) # Relevant comment    b = stack.enter_context(Dummy()) # Comment about b    c = stack.enter_context(Dummy()) # Further information

This is equivalent to

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

This has the benefit that you can generate your context managers in a loop instead of needing to separately list each one. The documentation gives the example that if you want to open a bunch of files, and you have the filenames in a list, you can do

with ExitStack() as stack:    files = [stack.enter_context(open(fname)) for fname in filenames]

If your context managers take so much screen space that you want to put comments between them, you probably have enough to want to use some sort of loop.


As Mr. Deathless mentions in the comments, there's a contextlib backport on PyPI under the name contextlib2. If you're on Python 2, you can use the backport's implementation of ExitStack.


Incidentally, the reason you can't do something like

with (        ThingA() as a,        ThingB() as b):    ...

is because a ( can also be the first token of the expression for a context manager, and CPython's current parser wouldn't be able to tell what rule it's supposed to be parsing when it sees the first (. This is one of the motivating examples for PEP 617, which introduces a much more powerful new parser, so the syntax you wanted may soon exist.


This seems tidiest to me:

with open('firstfile', 'r') as (f1 # first  ), open('secondfile', 'r') as (f2 # second  ):    pass


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.