Using hash to see if object's attributes have changed

Bryan bryanvick at gmail.com
Fri Dec 11 13:03:06 EST 2009


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.

I imagine it working something like this:

def getValues(obj):
	return [obj.a, obj.b, obj.c]

foo = Obj()
foo.a = foo.b = foo.c = 1
stateBefore = hashlib.sha1(str(getValues(foo)))
foo.b = 'changed'
stateNow = hashlib.sha1(str(getValues(foo)))
assert stateBefore != stateNow


I originally thought about running the hash on the __dict__ attribute,
but there may be things in there that don't actually constitute the
object's state as far as the database is concerned, so I thought it
better to have each object be responsible for returning a list of
values that constitute its state as far as the DB is concerned.

I would appreciate any insight into why this is a good/bad idea given
your past experiences.



More information about the Python-list mailing list