[Python-Dev] With statement

Gerald S. Williams gsw@agere.com
Tue, 4 Feb 2003 13:56:27 -0500


Paul Moore wrote:
>     'with' expr ':'
>         suite

Yes, simplicity is good. I don't buy the arguments for
replacing:

    suite_user = expr
    with suite_user:
        suite

with:

    with suite_user = expr:
        suite

The arguments in favor of the latter could be applied
to 'while' (or even 'if') as well. I know you don't
have to worry about '=' being confused for '==' in
this case, but is the gain here enough to warrant the
inconsistency?

It's interesting to note that with Guido's proposal,
your example [slightly paraphrased here]:

>     class autolock:
>         def __init__(self, l): self.l = l
>         def __enter__(self):   self.l.acquire()
>         def __exit__(self):    self.l.release()
> 
>     with autolock(lock()):
>         # work with the lock held

Could be coded like this, given the right implementation
of with_block:

    class with_autolock(with_block):
        def __init__(self, l): with_block.__init__(self); self.l = l
        def __enter__(self):   self.l.acquire()
        def __exit__(self):    self.l.release()

    with_autolock(lock()):
        # work with the lock held

(If support for multiple thunk users is added back, the
'with' could probably be added back to the example also.)

-Jerry