Python object that monitors changes in objects

hash, python

Solution

Here is an implementation for you. Note that the objects you monitor must be hashable and picklable. Note also the use of a `WeakKeyDictionary` which means that the `Monitor` won't stop the monitored objects from being deleted.

from weakref import WeakKeyDictionary
from cPickle import dumps

class Monitor():
    def __init__(self):
        self.objects = WeakKeyDictionary()
    def is_changed(self, obj):
        current_pickle = dumps(obj, -1)
        changed = False
        if obj in self.objects:
            changed = current_pickle != self.objects[obj]
        self.objects[obj] = current_pickle
        return changed

class MyObject():
    def __init__(self):
        self.i = 1
    def change_somehow(self):
        self.i += 1

If you test it like this

object1 = MyObject()
monitor = Monitor()
print monitor.is_changed(object1)
object1.change_somehow()
print monitor.is_changed(object1)
print monitor.is_changed(object1)

It prints

False
True
False

Problem

I want a Python object that will monitor whether other objects have changed since the last time they were checked in, probably by storing their hash and comparing. It should behave sort of like this: ``` >>> library = Library() >>> library.is_changed(object1) False >>> object1.change_somehow() >>> library.is_changed(object1) True >>> library.is_changed(object1) False ``` Do you know of anything like that?

Original source