[Python-Dev] With statement

Moore, Paul Paul.Moore@atosorigin.com
Tue, 4 Feb 2003 17:02:05 -0000


From: Neal Norwitz [mailto:neal@metaslash.com]
> 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 =3D file(filename):
>             # protected code
>         except:
>             # handle exception

I'd say no. Use either

    # Protects the cleanup as well
    try:
        # You do realise you can't use a raw file object here really?
        with my_file =3D file(filename):
            # protected code
    except:
        # handle exception

or

    # Just protects the code using the file
    with my_file =3D file(filename):
        try:
            # protected code
        except:
            # handle exception

The fact that there are 2 options, either of which has arguments in
favour, indicates to me that it should be explicit.

In any case, with is a form of try ... finally, and that doesn't
allow an except clause either.

Paul.