[Python-Dev] PEP 343 - Abstract Block Redux

Ron Adam rrr at ronadam.com
Mon May 16 05:21:12 CEST 2005


It's been interesting watching all the loops this discussion has gone 
through.  I'm not sure the following is compatible with the current 
proposals, but maybe it will spur some ideas or help rule out something.

There have been several examples of problems with opening several 
resources inside an enter method and how to resolve them in the case of 
an incomplete entry.

So it seams to me, each resource needs to be handled separately, but 
that doesn't mean you can't use them as a group.

So I was wondering if something like the following is feasible?


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

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


The 'with' (or whatever) statement would need a little more under the 
hood, but it might simplify handling multiple resources.

This also reduces nesting in cases such as locking and opening. Both 
must succeed before the block executes. And if something goes wrong, the 
"with" statement knows and can handle each resource.  The point is, each 
resource needs to be a whole unit, opening multiple files in one 
resource handler is probably not a good idea anyway.

Regards,
_Ron Adam



More information about the Python-Dev mailing list