[Python-ideas] unpacking context managers in WITH statement

Mathias Panzenböck grosser.meister.morti at gmx.net
Fri Feb 3 17:30:12 CET 2012

Of course there is something to replace nested:

 >>> with open("egg.txt","w") as egg, open("spam.txt","w") as spam:
 >>>     egg.write("egg")
 >>>     spam.write("spam")

The nested function was removed because it is broken. E.g. take this:

 >>> with nested(open("egg.txt","w"), open("spam.txt","w")) as egg, spam:
 >>>     egg.write("egg")
 >>>     barspamwrite("spam")

What if opening of spam.txt produces an exception? Then egg.txt will never be closed! The new with 
syntax takes care of this. It basically rewrites it as:

 >>> with open("egg.txt","w") as egg:
 >>>     with open("spam.txt","w") as spam:
 >>>         egg.write("egg")
 >>>         spam.write("spam")

On 02/03/2012 04:09 PM, Yury Selivanov wrote:
> Hello,
> With the removal of "contextlib.nested" in python 3.2 nothing was introduced to replace it.  However, I found it pretty useful, despite the fact that it had its own quirks.  These quirks can (at least partially) be addressed by allowing unpacking syntax in the context manager.
> Consider the following snipped of code:
>    ctxs = ()
>    if args.profile:
>        ctxs += (ApplicationProfilerContext(),)
>    if args.logging:
>        ctxs += (ApplicationLoggingContext(),)
>    with *ctxs:
>        Application.run()
> As of now, without "nested" we have either option of reimplementing it, or to write lots of ugly code with nested 'try..except's.  So the feature was taken out, but nothing replaced it.
> What do you think guys?
> Thanks,
> Yury
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas

More information about the Python-ideas mailing list