pythonic way to free resources

Bengt Richter bokr at oz.net
Thu Aug 15 17:43:51 EDT 2002


On Wed, 14 Aug 2002 14:01:44 -0500, Skip Montanaro <skip at pobox.com> wrote:
[...]
>
>Also, note that you should initialize the object before the try:
>
Might want to catch a failed attempt at that initialization too?

try:
>    f1 = file(...)
>    try:
>        # do stuff with f1
>        f2 = file(...)
>        try:
>            # do stuff with f2
>        finally:
>            f2.close()
>    finally:
>        f1.close()
except IOError, e:
     print "Couldn't get past square one, due to: %s." % e
>
>Sort of messy, but effective.
>

Hm, just thought of this (untested!):
Given

    class Finalizer:
        def finalize(self):
            for f in self.__dict__.values():
                f.close()
            
one could use a single try block and do better error reporting, e.g.,

    fin = Finalizer()
    try:
        fin.f1 = f1 = file(...)
        # do stuff with f1
        fin.f2 = f2 = file(...)
        # do stuff with f2
    except IOError, e:
         print "An IO Error prevented success: %s." % e
    except Exception, e:
         print "Exception during f1 or f2 processing: %s." % e
    # release all resources successfully allocated and logged
    fin.finalize()

You could use the same mechanism for non-file resources by having
a call to a complex resource-allocating function return a cleanup
object that had a .close() method. It wouldn't have to be used for
file purposes (or anything at all) within the try, yet it would serve
as a kind of finalization guarantee against subsequent exceptions
within the try, so you wouldn't need all the nested try/finally blocks.

Regards,
Bengt Richter



More information about the Python-list mailing list