[Python-Dev] exec/with thunk-handling proposal

Jeff Epler jepler@unpythonic.net
Tue, 4 Feb 2003 08:15:46 -0600


On Tue, Feb 04, 2003 at 01:03:24PM +0100, Alex Martelli wrote:
> On Tuesday 04 February 2003 12:54 pm, holger krekel wrote:
>    ...
> >     f1=open(inputfn)
> >     with autoclose(f1):
> >         f2 = open(outputfn, 'w')
> >         with autoclose(f2):
> >             for line in f1:
> >                 ...
> >                 f2.write(line)
> >
> > I think there should be a better solution for multiple ressources.
> 
> I agree this is slight too cumbersome, and deeply wish it was
> feasible to go with:
> 
>      with f1=autoclose(inputfn):
>          with f2=autoclose(outputfn, 'w'):
>              for line in f1:
>                  ...
>                  f2.write(line)
> 
> i.e., nested with's would be just fine, IF binding the with'd expression
> to a name was allowed as part of the with statement, by whatever sugar.  

This made me realize something.  What happens if some sort of exception
is raised between 'f1 = open()' and the start of the block 'with
autoclose(f1):'?  KeyboardInterrupt could be raised between the
statements, for instance.  autoclose(f1).__exit__() will never be called
now, since autoclose(f1) is never even computed.

Even if assignment in the statement is supported (
'with f1 = autoclose(outputfn, "w")') I don't immediately see what
bytecode would be written to make sure that an exception didn't arrive
at just the wrong moment, leaving 'with' block incompletely entered but
with the file open.

Doesn't this concern apply to the common idiom
    l.acquire()
    try:
        pass
    finally:
        l.release()
too?  (most of the 'with' proposals are suggested to be equivalent to
a Python program of this structure)  The exception could be delivered
just before the POP_TOP of the acquire statement, or the SET_LINENO of
the try: statement, and things would go south from there.

Please let me know what simple fact I'm missing.

Jeff