watching mutables?
Skip Montanaro
skip at pobox.com
Fri Sep 27 13:03:03 EDT 2002
Anton> Variables should be 'marked' to install this function for
Anton> them. For example 'watch(m,f)' indicates that function f is
Anton> called if mutable variable m is changed.
You could implement a proxy object which delegates to the real object and
catches all __setattr__ and __setitem__ calls. Something like:
class MutableProxy:
def __init__(self, obj):
self.__dict__['obj'] = obj
def __setattr__(self, attr, val):
print "Hey! My %s attribute got diddled!" % attr
setattr(self.__dict__['obj'], attr, val)
def __getattr__(self, attr):
return getattr(self.__dict__['obj'], attr)
if __name__ == "__main__":
class Dummy:
pass
d = MutableProxy(Dummy())
d.x = 1
print d.x
__setitem__ and __getitem__ are similar, but you have to worry about ranges.
You'd probably have to wrap __call__ as well.
There's probably a way to do it with metaclasses, but ... ooh! I just got a
headache, better back off before my brain expl ... <* blam! *>
--
Skip Montanaro - skip at pobox.com
"Airplanes don't fly until the paperwork equals the weight of the
aircraft. Same with i18N." - from the "Perl, Unicode and i18N FAQ"
More information about the Python-list
mailing list