Default scope of variables

Ethan Furman ethan at stoneleaf.us
Sun Jul 7 14:59:28 EDT 2013


On 07/07/2013 06:43 AM, Chris Angelico wrote:
>
> The 'with' statement doesn't allow this. I would need to use some kind
> of magic to rebind the old transaction to the name, or else use a list
> that gets magically populated:
>
> with new_transaction(conn) as tran:
>      tran[-1].query("blah")
>      with subtransaction(tran):
>          tran[-1].query("blah")
>          with subtransaction(tran):
>              tran[-1].query("blah")
>              # roll this subtransaction back
>          tran[-1].query("blah")
>          tran[-1].commit()
>      tran[-1].query("blah")
>      tran[-1].commit()

The other option is to build the magic into the new_transaction class, then your code will look like:

  with new_transaction(conn) as tran:
       tran.query("blah")
       with tran.subtransaction():
           tran.query("blah")
           with tran.subtransaction():
               tran.query("blah")
               # roll this subtransaction back
           tran.query("blah")
           tran.commit()
       tran.query("blah")
       tran.commit()

This would definitely make more sense in a loop.  ;)

--
~Ethan~



More information about the Python-list mailing list