[Python-Dev] With statement

Neal Norwitz neal@metaslash.com
Tue, 04 Feb 2003 11:57:01 -0500


On Tue, Feb 04, 2003 at 04:45:28PM -0000, Moore, Paul wrote:
> From: Duncan Booth [mailto:duncan@rcp.co.uk]
> > Your autoclose example doesn't use __enter__, and your autolock example 
> > would work just as well if you moved the __enter__ code into __init__ 
> > (although then you couldn't write it the alternative way you suggest).
> 
> > Do you have any good examples that actually require __enter__, or could it 
> > be dropped for even more simplicity?
> 
> My actual preference is for a lock object with enter = acquire and
> leave = release. Then, the idiom is
> 
>     with my_lock:
>         # protected code
> 
> This requires a separate enter hook.

I agree this code should be preferred.  I also think the assignment
should be optional.  Same idea works for files.

        with my_file = file(filename):
            # protected code

One thing I'm thinking about is, should there be an except clause?
For example, if you want to tell the user writing the file failed,
how would you do that?  Would the following be decent?

        with my_file = file(filename):
            # protected code
        except:
            # handle exception

Neal