Default scope of variables
frank at chagford.com
Thu Jul 11 07:52:32 CEST 2013
"Ian Kelly" <ian.g.kelly at gmail.com> wrote in message
news:CALwzidk2+b5bYM5B+XVtoZ8LHeyVHcos4v58F8Z2o1Jb6sAzog at mail.gmail.com...
> On Tue, Jul 9, 2013 at 11:54 PM, Frank Millman <frank at chagford.com> wrote:
>> You had me worried there for a moment, as that is obviously an error.
>> Then I checked my actual code, and I find that I mis-transcribed it. It
>> actually looks like this -
>> with db_session as conn:
>> db_session.transaction_active = True
>> I am still not quite sure what your objection is to this. It feels
>> straightforward to me.
>> Here is one possible answer. Whenever I want to commit a transaction I
>> to add the extra line. There is a danger that I could mis-spell
>> 'transaction_active', in which case it would not raise an error, but
>> not commit the transaction, which could be a hard-to-trace bug. Using
>> approach, if I mis-spelled 'db_session.connect()', it would immediately
>> raise an error.
>> Is that your concern, or are there other issues?
> Yes, that is one concern. Another is that since you mistakenly typed
> "conn" instead of "db_session" once, you might make the same mistake
> again in actual code, with the same effect (unless the conn object
> doesn't allow arbitrary attributes, which is a possibility). Another
> is that the code adheres better to the DRY principle if you don't need
> to copy that line all over the place.
Thanks to you and Ethan - that does make sense.
I have reviewed my code base to see how many occurrences there are, and
there are just three.
All database objects inherit from a DbOject class. The class has a save()
method and a delete() method. Each of these requires a commit, so I use my
technique there. All database updates are activated by calling save() or
I have an init.py script to 'bootstrap' a brand new installation, which
requires populating an empty database with some basic structures up front.
DbObject cannot be used here as the required plumbing is not in place, so I
use my technique here as well.
However, this does not invalidate your general point, so I will keep it in
More information about the Python-list