Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python object that monitors changes in objects

Tags:

python

hash

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?

like image 918
Ram Rachum Avatar asked Oct 15 '09 19:10

Ram Rachum


People also ask

Can Python object type change?

Every object in Python is classified as immutable (unchangeable) or not. In terms of the core types, numbers, strings, and tuples are immutable; lists and dictionaries are not (they can be changed in-place freely).

Can objects contain objects Python?

Any old object might not be able to contain other objects; e.g. int s are objects too and can't contain other objects. Technically no object in Python actually contains other objects, they just refer to them.

What are objects in Python?

An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values. Python is object-oriented programming language that stresses on objects i.e. it mainly emphasizes functions.


2 Answers

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
like image 174
Nick Craig-Wood Avatar answered Oct 03 '22 23:10

Nick Craig-Wood


It sounds like you're describing the observer pattern. Check here:

  • http://rudd-o.com/projects/python-observable/
  • Twisted observable
  • http://radio.weblogs.com/0124960/2004/06/15.html#a30 - includes explanation
like image 42
Corbin March Avatar answered Oct 03 '22 23:10

Corbin March