Default scope of variables

alex23 wuwei23 at gmail.com
Tue Jul 9 00:52:41 EDT 2013


On 7/07/2013 11:43 PM, Chris Angelico wrote:
> Yep. There's a problem, though, when you bring in subtransactions. The
> logic wants to be like this:
>
> with new_transaction(conn) as tran:
>      tran.query("blah")
>      with tran.subtransaction() as tran:
>          tran.query("blah")
>          with tran.subtransaction() as tran:
>              tran.query("blah")
>              # roll this subtransaction back
>          tran.query("blah")
>          tran.commit()
>      tran.query("blah")
>      tran.commit()
>
> The 'with' statement doesn't allow this.

I'd take the 'explicit is better than implicit' approach to naming the
context managers here and rather than use 'tran' choose names that
reflect for what the transaction is to be used ie summarising what's in
the "blah" of each query.

with new_transaction(conn) as folder_tran:
     folder_tran.query("blah")
     with folder_tran.subtransaction() as file_tran:
         file_tran.query("blah")
         with file_tran.subtransaction() as type_tran:
             type_tran.query("blah")

(for want of a better heirachical example...)



More information about the Python-list mailing list