[Python-Dev] anonymous blocks

Nick Coghlan ncoghlan at gmail.com
Sat Apr 23 01:48:40 CEST 2005


Shane Hathaway wrote:
> There's a lot of boilerplate code there.  Using your suggestion, I could
> write that something like this:
> 
>     def transaction():
>         begin_transaction()
>         try:
>             continue
>         except:
>             abort_transaction()
>             raise
>         else:
>             commit_transaction()
> 
>     with transaction():
>         changestuff()
>         changemorestuff()

For that to work, the behaviour would need to differ slightly from what I 
envisioned (which was that the 'continue' would be behaviourally equivalent to a 
'yield None').

Alternatively, something equivalent to the above could be written as:

def transaction():
   begin_transaction()
   continue
   ex = sys.exc_info()
   if ex[0] is not None:
     abort_transaction():
   else:
     commit_transaction():

Note that you could do this with a normal resource, too:

class transaction(object):
   def __enter__():
       begin_transaction()

   def __exit__():
     ex = sys.exc_info()
     if ex[0] is not None:
       abort_transaction():
     else:
       commit_transaction():

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net


More information about the Python-Dev mailing list