[Python-Dev] multi-with statement

Georg Brandl g.brandl at gmx.net
Sat May 2 22:12:10 CEST 2009


Fredrik Johansson schrieb:
> On Sat, May 2, 2009 at 9:01 PM, Georg Brandl <g.brandl at gmx.net> wrote:
>> Hi,
>>
>> this is just a short notice that Mattias Brändström and I have finished a
>> patch to implement the previously discussed and mostly warmly welcomed
>> extension to with's syntax, allowing
>>
>>   with A() as a, B() as b:
>>
>> to be written instead of
>>
>>   with A() as a:
>>       with B() as b:

> I was hoping for the other syntax in order to be able to create a
> nested context in advance as a simple tuple:
> 
> with A, B:
>     pass
> 
> context = A, B
> with context:
>     pass
> 
> (I.e. a tuple, or perhaps any iterable, would be a valid context manager.)

I see; you want to construct your context manager programmatically and pass
it to "with" without knowing what is in there.

While this would be possible, we have to be aware that with this we would
effectively change the context manager protocol, rather like the iterator
protocol's __getitem__ alternate realization.  This muddies the definition
of a context manager.

(The interesting thing is that you could already implement *that* version
without any new syntactic support, by giving tuples an __enter__/__exit__
method pair.)

> With the syntax in the patch, I will still have to implement a custom
> nesting context manager to do this, which sort of defeats the purpose.

Not really.  Having an unknown number of stacked context managers is not
the purpose -- for that, I'd still say a custom nesting context manager
is better, because it is also more explicit when created not at the "with"
site.  (You could even write it as a tuple subclass, if you like the tuple
interface.)

Georg

-- 
Thus spake the Lord: Thou shalt indent with four spaces. No more, no less.
Four shall be the number of spaces thou shalt indent, and the number of thy
indenting shall be four. Eight shalt thou not indent, nor either indent thou
two, excepting that thou then proceed to four. Tabs are right out.



More information about the Python-Dev mailing list