Default scope of variables

Ian Kelly ian.g.kelly at gmail.com
Tue Jul 9 03:56:29 EDT 2013


On Tue, Jul 9, 2013 at 1:35 AM, Frank Millman <frank at chagford.com> 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 would also probably make db_session a factory function instead of a global.



More information about the Python-list mailing list