Using hash to see if object's attributes have changed

Robert Kern robert.kern at gmail.com
Fri Dec 11 13:17:00 EST 2009


On 2009-12-11 12:03 PM, Bryan wrote:
> When a user submits a request to update an object in my web app, I
> make the changes in the DB, along w/ who last updated it and when.  I
> only want to update the updated/updatedBy columns in the DB if the
> data has actually changed however.
>
> I'm thinking of having the object in question be able to return a list
> of its values that constitute its state.  Then I can take a hash of
> that list as the object exists in the database before the request, and
> then on the object that the user has made changes to.  If they are not
> equal, the user has changed the object.

It *might* work, but probably won't be robust especially as you are relying on 
the string representation. You would be much better off using an ORM, which will 
do all of this for you. This is exactly what they are for.

They usually determine whether attributes have change by instrumentation rather 
than inspection. If you still don't want to use a full ORM, you should at least 
emulate that strategy. Add descriptors to your classes for each attribute you 
want to map to a column. On __set__, they should compare the new value to the 
old, and set a "dirty" flag if the the attribute changes value. Or just 
implement __setattr__ on your classes to do a similar check.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list