Nested with statements
Hi! 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 existence. 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). Regards, Mattias
On 27 Apr 2009, at 20:33, Mattias Brändström wrote:
[...]
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.
There was a discussion about this on this list: http://mail.python.org/pipermail/python-ideas/2009-March/003188.html I can't remember the outcome. -- Arnaud
2009/4/27 Arnaud Delobelle <arnodel@googlemail.com>:
On 27 Apr 2009, at 20:33, Mattias Brändström wrote:
[...]
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.
There was a discussion about this on this list:
http://mail.python.org/pipermail/python-ideas/2009-March/003188.html
I can't remember the outcome.
Oh. Thanks for pointing that out. I'll try and contribute to that thread instead. :.:: mattias
Le Mon, 27 Apr 2009 20:54:58 +0100, Arnaud Delobelle <arnodel@googlemail.com> s'exprima ainsi:
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.
There was a discussion about this on this list:
http://mail.python.org/pipermail/python-ideas/2009-March/003188.html
I can't remember the outcome.
There was no clear outcome, for sure ;-) Except maybe it was stated that with A(), B() as a,b: should rather be spelled with A() as a, B() as b: to reuse the syntax of imports. Denis ------ la vita e estrany
participants (3)
-
Arnaud Delobelle
-
Mattias Brändström
-
spir