[Python-Dev] PEP 343 - Abstract Block Redux

Ron Adam rrr at ronadam.com
Mon May 16 07:04:15 CEST 2005


A additional comment (or 2) on my previous message before I go back to 
lurk mode.

If the recommended use of each resource template is kept to a single 
resource, then each enter and exit can be considered a whole block of 
code that will either pass or fail. You can then simplify the previous 
template to just:


# open-close pairing
def opening(filename, mode):
     def openfile():
         f = open(filename, mode)
         yield f
         f.close()
     return openfile

with opening(file1,m),opening(file2,m),opening(file3,m) as f1,f2,f3:
     # do stuff with files


The with statement will need to catch any opening errors at the start in 
case one of the opening resources fails.  Close any opened resources, 
then re raise the first exception.

The with statement will also need to catch any uncaught exceptions in 
the block, close any opened resources, then re raise the exception.

And again when closing, it will need to catch any exceptions that occur 
until it has tried to close all open resources, then re raise the first 
exception.

Although it's possible to have more than one exception occur, it should 
always raise the first most one as any secondary exceptions may just be 
a side effect of the first one.

The programmer has the option to surround the 'with' block with a try 
except if he want to catch any exceptions raised.

He should also be able to put try excepts before the yield, and after 
the yield, or in the block. (But not surrounding the yield, I think.)

Of course he may cause himself more problems than not, but that should 
be his choice, and maybe he thought of some use.

This might be an acceptable use case of try-except in the enter section.

def openfile(firstfile, altfile, mode):
     try:
         f = open(firstfile, mode)
     except:
         f = open(altfile, mode)
     yield f
     f.close()
return openfile


This is still a single open resource (if it succeeds) so should work ok.

Alternate closing could be possible, maybe retrying the close several 
time before raising it and letting the 'with' handle it.

Cheers,
_Ron





More information about the Python-Dev mailing list