Default scope of variables

Ethan Furman ethan at stoneleaf.us
Wed Jul 10 17:29:24 CEST 2013


On 07/09/2013 10:54 PM, Frank Millman wrote:
>
> "Ian Kelly" <ian.g.kelly at gmail.com> wrote in message
> news:CALwzidnf3Obe0eNf3xTHLj5a40K8HxVThVEipECQ8+34ZxyLxw at mail.gmail.com...
>> On Tue, Jul 9, 2013 at 10:07 AM, Ethan Furman <ethan at stoneleaf.us> wrote:
>>> You could also do it like this:
>>>
>>>      def updating(self):
>>>          self.transaction_active = True
>>>          return self
>>
>> Yes, that would be simpler.  I was all set to point out why this
>> doesn't work, and then I noticed that the location of the
>> "transaction_active" attribute is not consistent in the original code.
>> The DbSession class places it on self, and then the example usage
>> places it on the connection object (which I had based my version on).
>> Since that seems to be a source of confusion, it demonstrates another
>> reason why factoring this out is a good thing.
>
> 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?

That concern is big enough.  I've been bitten by that type of thing enough in my own code to want to avoid it where 
possible.  Plus the `with db_session.updating() as conn:` saves keystrokes.  ;)

--
~Ethan~



More information about the Python-list mailing list