[Python-Dev] With statement
Moore, Paul
Paul.Moore@atosorigin.com
Tue, 4 Feb 2003 11:58:15 -0000
I'm rapidly tending towards a preference for extreme simplicity in the =
with
statement. My basic logic is that the C++ idiom for all this is pretty
minimal, and works well (even though C++ has no "finally" equivalent, so =
the
need is more pressing in C++).
So, my current feeling is:
'with' expr ':'
suite
expands to
_x =3D expr
if hasattr(_x, '__enter__'):
_x.__enter__()
try:
suite
finally:
if hasattr(_x, '__exit__'):
_x.__exit__()
where _x is a hidden variable unavailable to the user.
And that's it. No assignment, no exception handling, no multiple =
expressions.
The two use cases we've been looking at (locks and files) can be coded =
as:
class autoclose:
def __init__(self, f):
self.f =3D f
def __exit__(self):
self.f.close()
f =3D open("whatever")
with autoclose(f):
# Use f
and
class autolock:
def __init__(self, l):
self.l =3D l
def __enter__(self):
self.l.acquire()
def __exit__(self):
self.l.release()
l =3D lock() # or whatever
with autolock(l):
# work with the lock held
(Thanks to Oren Tirosh for pointing out these idioms). Having autolock =
as a
subclass of lock also reads OK ("with l:" for "with the lock l held"), =
but I
don't think the file example reads well when expressed this way.
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?)
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...
Paul.