I’m trying to create a handler which triggers whenever any of object’s attributes’ value changes. I’m still quite new with python, and didn’t really come up with any working ways. This is what I did, and I know it can’t work like this, it’s just to show what I’m trying to achieve:
# ../handler.py
import copy
class Handler:
def __init__(self, obj):
# Let the object know it's handler
obj.handler = self
# Copy the object
self.copy = copy.deepcopy(obj)
# Let handler know it's object
self.obj = obj
# Handler not running atm.
self.running = False
def start(self):
# Running
self.running = True
# As long as running...
while self.running:
# Loop through all objects attributes
for attr in self.obj.__dict__:
# If attribute's value has changed
if self.copy.__dict__[attr] != self.obj.__dict__[attr]:
# Print out a message
print("%s was changed to %s" %(attr, self.obj.__dict__[attr]))
# Update the value to our copy
self.copy.__dict__[attr] = self.obj.__dict__[attr]
def stop(self):
# Not running
self.running = False
Here’s the main file
# ../main.py
from handler import Handler
class Value:
def __init__(self, v=None):
self.value = v
def createObject(v):
obj = Value(v)
Handler(obj)
return obj
myObj = createObject(5)
myObj.handler.start()
This will, however, result into this text getting printed out: handler was changed to <Handler.Handler object at 0x0000000002B1FC50> but I’m not changing the handler here? Also, the program will freeze, due to the while loop inside the Handler.start() function… How could I implement this in a working way?
You effectively want a proxy, and here’s a bit of a start…
You’ll also need to look for
__setattribute__and__delattribute__and other magic methods…How you’d cater for when the attribute changes could be a bit trickier – as you’d have to know if method calls existed which changed the object inplace… (such as
appendabove)A quick Google comes up with: http://code.activestate.com/recipes/496741-object-proxying/