[Python-Dev] With statement
Alex Martelli
aleax@aleax.it
Tue, 4 Feb 2003 13:24:12 +0100
On Tuesday 04 February 2003 12:58 pm, Moore, Paul wrote:
...
> Alex Martelli suggested transactional processing may be a reasonable use
> case for needing exception handling (commit in __exit__ and rollback in
> __except__) but I don't think the gain is worth the extra complexity - I'd
> say leave this coded as now with try...except..else. (Alex - care to
> convince me otherwise?)
Unless somebody can think of other use cases, I think it's reasonable
to say that try/except/else can take care of such transactional needs.
I still don't think splitting the typical need for "with x = expr:" into two
statements (x=expr first, then with x:) is optimal (even though in the
case of the lock you might not need that, you do need it again as
soon as it needs to be e.g. a Condition instead of a Lock -- basically
any time you need the expr in the body, which I'd say is most often,
quite differently from with and if and much closer to for). When you
nest with statements (and I agree that having only ONE thingy per
with is fine, so nested with statements are the way to go), it's even
less pleasant, IMHO.
To put it another way: is the advantage of:
f = open("whatever")
with autoclose(f):
# Use f
sufficient with respect to the existing alternative:
f = open("whatever")
try:
# Use f
finally: f.close()
to be worth introducing a new kind of statement? I see 3 lines
(4 if you insist on breaking after "finally:" of course) -- plus the
body "# Use f" of course -- with the existing alternative, versus
two with the new statement. With name binding,
with f = autoclosedfile("whatever"):
# Use f
we're down to 1, and in this case the advantage strikes me
as substantial. It would also be more natural for people who
are used to coding "resource acquisition is initialization" in
C++, since in that case, too, a name is always required
(whether you use it or not in the following block):
{
autoclosedfile f("whatever");
// Use f
}
> If anyone feels a need for more than this, please supply a use case - I
> can't think of anything concrete. Otherwise, this is what I'm going to put
> in the PEP...
As long as you mention in the PEP the ardent wish of some of
us for name binding within 'with', np -- I can't see any other "use
case" for binding-within-with save for the fact that it seems such
a frequent need, and almost necessary to make 'with' enough of
a win to justify its existence;-).
Alex