Default scope of variables

Frank Millman frank at chagford.com
Tue Jul 9 10:22:48 CEST 2013


"Chris Angelico" <rosuav at gmail.com> wrote in message 
news:CAPTjJmr4Mr0qCGWqXwyvDCZ55NuaV79VbTT8BJNDSDvhrKq15w at mail.gmail.com...
> On Tue, Jul 9, 2013 at 5:35 PM, Frank Millman <frank at chagford.com> wrote:
>> I have been following this sub-thread with interest, as it resonates with
>> what I am doing in my project.
>
> Just FYI, none of my own code will help you as it's all using libpqxx,
> but the docs for the library itself are around if you want them (it's
> one of the standard ways for C++ programs to use PostgreSQL).
>

I support multiple databases (PostgreSQL, MS SQL Server, sqlite3 at this 
stage) so I use generic Python as much as possible.

>> I came up with the following context manager -
>>
>> class DbSession:
>>     def __exit__(self, type, exc, tb):
>>             if self.transaction_active:
>>                 self.conn.commit()
>>                 self.transaction_active = False
>
> Hmm. So you automatically commit. I'd actually be inclined to _not_ do
> this; make it really explicit in your code that you now will commit
> this transaction (which might throw an exception if you have open
> subtransactions).
>

I endeavour to keep all my database activity to the shortest time possible - 
get a connection, execute a command, release the connection. So setting 
'transaction_active = True' is my way of saying 'execute this command and 
commit it straight away'. That is explicit enough for me. If there are 
nested updates they all follow the same philosophy, so the transaction 
should complete quickly.

Frank






More information about the Python-list mailing list