[Python-Dev] PEP 340: syntax suggestion - try opening(filename) as f:

Jim Jewett jimjjewett at gmail.com
Fri Apr 29 21:01:20 CEST 2005


Michael Spencer:

> I don't know whether it's true for all the PEP 340 use cases, but the all the 
> current examples would read very naturally if the block-template could be 
> specified in an extended try statement:

>>     1. A template for ensuring that a lock, acquired at the start of a
>>        block, is released when the block is left:

> try with_lock(myLock):
>      # Code here executes with myLock held.  The lock is
>      # guaranteed to be released when the block is left (even
>      # if by an uncaught exception).

So we would have 

try ... finally, try ... except, and try (no close).

It works for me, and should be backwards-compatible.

The cases where it doesn't work as well are

(1)  You want to insert several different suites.
    
But the anonymous yield syntax doesn't work well for that either.
(That is one of the arguments for thunks instead of generator abuse.)

(2)  You really do want to loop over the suite.  Try doesn't imply a loop.

But this is a *good* thing.  Resources are not loops, and you can always
make the loop explicit as iteration over the resource

    def opener(file):
        f=open(file)
        try:
            yield f
        finally:
            f.close()
        
    try opener(file) as f:
        for line in f:
            process(line)


More information about the Python-Dev mailing list