[Python-Dev] exec/with thunk-handling proposal

Walter Dörwald walter@livinglogic.de
Tue, 04 Feb 2003 16:30:47 +0100


holger krekel wrote:

 > [...]
> I think we can may get away with only a "weak" keyword
> and allow the aforementioned encapsulation of execution 
> events into an object like this:
> 
>     exec expr [with params]: suite
> 
> where the expression is evaluated to return a
> "thunk" handler with these optional "execution" hooks:
> 
>     def __enter__(self):  
>         "before suite start"
> 
>     def __except__(self, type, value, tb): 
>         "swallow given exception, reraise if neccessary"
> 
>     def __leave__(self):
>         """upon suite finish (not called if __except__ 
>            exists and an exception happened)
>         """

Why not simply have one method

    def __execute__(self, thunk):

which gets passed the thunk. This method can do anything it
likes before executing the thunk, it can do anything after
executing the thunk, and it can implement exception handling:

    class twice:
        def __execute__(self, thunk):
            print "start"
            try:
               thunk()
               print "once"
               thunk()
               print "twice"
            except Exception, exc:
               print "exception", ext
            else:
               print "OK"

Then you can do:

     exec twice():
         for i in xrange(10):
             print i

Bye,
    Walter Dörwald