[Python-ideas] with-statement syntactic quirk

Nick Coghlan ncoghlan at gmail.com
Thu Nov 1 12:40:41 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>.
> Legal:
>>>> 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):
>           pass
> 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).
> Of course, you can wrap with backslashes, but ick!

I've been remiss in not mentioning the new alternative in 3.3 for
handling nesting of complex context management stacks:

    with contextlib.ExitStack() as cm:
        p1 = cm.enter_context(open('/etc/passwd'))
        p2 = cm.enter_context(open('/etc/passwd'))

(Note: ExitStack is really intended for cases where the number of
context managers involved varies dynamically, such as when you want to
make a CM optional, but you *can* use it for static cases if it seems


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list