[Python-ideas] unpacking context managers in WITH statement

Yury Selivanov yselivanov.ml at gmail.com
Fri Feb 3 17:36:53 CET 2012


This is not about explicitly writing comma-separated list of context
managers in the statement, but rather about ability to compose this list
dynamically.

With unpacking you won't have the problem of uncaught exception in
__new__/__init__, because such exception would propagate on the
stage of constructing the list of managers.  Exceptions occurred
during the with statement execution, i.e. in __enter__ and __exit__
methods will work just fine, or am I missing something?

On 2012-02-03, at 11:30 AM, Mathias Panzenböck wrote:

> 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
>> 
> 
> _______________________________________________
> 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