[Python-ideas] Nested with statements

Mattias Brändström thebrasse at brasse.org
Mon Apr 27 21:33:53 CEST 2009


Using contextlib.nested() often me headaches... (This is my first time
posting, so please bear with me...) :-)

I often want to write code similar to this:

with conextlib.nested(A(), B()) as a,b:
    # Code that uses a and b.

My problem is that if B() throws an exception then no context manager
will ever be created to release the resources that A() acquired. This
isn't really contextlib.nested's fault since it never comes into

It would be really useful to have a shorthand for creating truly
nested with statements. My idea then is this: couldn't the language be
tweaked to handle this? It might look something like this:

with A(), B() as a,b:
    # Code that uses a and b.

This would translate directly to:

with A() as a:
    with B() as b:
        # Code that uses a and b.

I really think that this approach to a shorthand for nested with
statements would be better than using contextlib.nested (and perhaps
this is what contextlib.nested intented to do from the beginning).


More information about the Python-ideas mailing list