Default scope of variables

Ian Kelly ian.g.kelly at gmail.com
Wed Jul 10 11:42:08 EDT 2013


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
>         conn.cur.execute(...)
>
> 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 have
> 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 would
> not commit the transaction, which could be a hard-to-trace bug. Using your
> 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.



More information about the Python-list mailing list