Default scope of variables

Ethan Furman ethan at
Tue Jul 9 18:07:58 CEST 2013

On 07/09/2013 01:38 AM, Frank Millman wrote:
> "Ian Kelly" <ian.g.kelly at> wrote in message
> news:CALwzid=FzgjPebifx1stDBkh8iwLtWggwwPTPhZ1ykYg+05wEg at
>> On Tue, Jul 9, 2013 at 1:35 AM, Frank Millman <frank at> wrote:
>>> When any of them need any database access, whether for reading or for
>>> updating, they execute the following -
>>>      with db_session as conn:
>>>          conn.transaction_active = True  # this line must be added if
>>> updating
>>>          conn.cur.execute(__whatever__)
>> I'd probably factor out the transaction_active line into a separate
>> DbSession method.
>>     @contextmanager
>>     def updating(self):
>>         with self as conn:
>>             conn.transaction_active = True
>>             yield conn
>> Then you can do "with db_session" if you're merely reading, or "with
>> db_session.updating()" if you're writing, and you don't need to repeat
>> the transaction_active line all over the place.
> I'll bear it in mind, but I will have to expend some mental energy to
> understand it first <g>, so it will have to wait until I can find some time.

You could also do it like this:

     def updating(self):
         self.transaction_active = True
         return self

and a sample object:

     class Tester(object):
         def __init__(self):
             self.transaction_active = False
             print 'initializied'
         def __enter__(self, *args):
             print '__enter__: transaction_active =', self.transaction_active
             return self
         def __exit__(self, *args):
             self.transaction_active = False
             print '__exit__: transaction_active =', self.transaction_active
         def updating(self):
             self.transaction_active = True
             print 'updating: self.transaction_active =', self.transaction_active
             return self

     with Tester() as conn:
         print 'in first with block'

     print '-' * 50

     with Tester().updating() as conn:
         print 'in second with block'

with it's test run:

     ethan at hydra:~$ python
     __enter__: transaction_active = False
     in first with block
     __exit__: transaction_active = False
     updating: self.transaction_active = True
     __enter__: transaction_active = True
     in second with block
     __exit__: transaction_active = False


More information about the Python-list mailing list