[Python-Dev] Extended Function syntax

Moore, Paul Paul.Moore@atosorigin.com
Mon, 3 Feb 2003 13:57:05 -0000


From: Michael Hudson [mailto:mwh@python.net]
>>> How would I do this elegantly without the assignment...?
>>
>> Just as you do with if:
>
> Good point.  "with" testlist ':' NEWLINE it is, if it's me
> that gets to write the PEP.

Are you saying that you don't see the value of

    with var =3D expr:
        suite

because it can be rewritten as

    var =3D expr
    with var:
        suite

? Hmm, I suppose so. But let's take a step back - what is the
"with" syntax for? It's a little more than a shorthand for a
try...finally block, because it has an encapsulation value as
well.

Consider

    try:
        f =3D open("blah.txt", "r")
        ...
    finally:
        f.close()

compared with

    # Here, the definition of autoclose is omitted, that's
    # exactly the point - we don't *care* how it's implemented,
    # it's just an open file that manages its resources for me

    with f =3D autoclose("blah.txt", "r"):
        ...

and with

    f =3D autoclose("blah.txt", "r")
    with f:
        ...

The problem with the third case as compared to the second is that
using autoclose() rather than open() has *no value* in the absence
of the with statement. And contrariwise, if x is an object which
hasn't been designed for use with the "with" construct, "with x"
is meaningless.

So I guess what I'm saying is that "with ... autoclose" only
make sense in combination. Putting the two on different lines loses
that connection. If you need to name the result of the autoclose()
call, you either allow the with construct to include the assignment,
or you lose that conceptual link.

Paul.