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

Michael Spencer mahs at telcopartners.com
Fri Apr 29 20:03:33 CEST 2005


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).

>     2. A template for opening a file that ensures the file is closed
>        when the block is left:

try opening("/etc/passwd") as f:
     for line in f:
         print line.rstrip()

> 
>     3. A template for committing or rolling back a database
>        transaction:
> 

try transaction(mydb):

>     4. A template that tries something up to n times:
> 
try auto_retry(3):
     f = urllib.urlopen("http://python.org/peps/pep-0340.html")
     print f.read()

>     5. It is possible to nest blocks and combine templates:

try with_lock(myLock):
     try opening("/etc/passwd") as f:
         for line in f:
             print line.rstrip()


Michael



More information about the Python-Dev mailing list