[RFC/MERGE][#243391] _run_and_cleanup helper (alternative to try/finally)

Aaron Bentley aaron at aaronbentley.com
Wed Oct 8 14:05:40 BST 2008


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Andrew Bennetts wrote:
> Hi all,
> 
> This patch is an extension of my fix for bug 230902 at
> <http://bundlebuggy.aaronbentley.com/request/%3C20081008054310.GC19754@steerpike.home.puzzling.org%3E>.
> 
> I'm looking for opinions on the API defined by the attached patch.

It looks sensible, but I wonder whether it goes far enough.

There are many situations where I want to run a method with multiple
cleanups, i.e. two tree.unlocks.  Either I wind up with deep-nested
try/finally blocks, or I define a stack of cleanups to run.

So I'm thinking about an object like:

class CleanupHandler(object):
    @classmethod
    def run_and_cleanup(klass, cleanup, kallable, *args, **kwargs):
        handler = klass()
        handler.add_cleanup(cleanup)
        handler.run(kallable, *args, **kwargs)

    def __init__(self):
        self.cleanups = []

    def add_cleanup(self, cleanup):
        self.cleanups.append(cleanup)

    def cleanup(self):
        for cleanup in reversed(self.cleanups):
            cleanup()

    def run(kallable, *args, **kwargs):
       try:
           result = kallable(*args, **kwargs)
       except:
           exc_info = sys.exc_info()
           try:
               self.cleanup()
           finally:
               raise exc_info[0], exc_info[1], exc_info[2]
       else:
           self.cleanup()
           return result

> But this demonstrates
> the main drawback of this approach: it typically requires defining a new
> function for no purpose other than to have code run from within
> _run_and_cleanup.

Without the 'with' keyword, the only I know to automate context
management is to wrap it in a callable.

As you noted, it bears some similarities to the lock decorators.
Perhaps it could be a decorator, too.

Aaron
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFI7LAk0F+nu1YWqI0RApvUAJ9+n2Uiz4c+wEu8dKh9K/ASiVMSHwCfYNBu
AZHKmeQvXUHqgl4uupF1TDk=
=w/mv
-----END PGP SIGNATURE-----



More information about the bazaar mailing list