I want to implement function which takes as argument any object and trackes changes of value for specific attribute. Than saves old value of attribute in old_name attribute.
For example:
class MyObject(object):
attr_one = None
attr_two = 1
Lets name my magic function magic_function()
Sot than i can do like this:
obj = MyObject()
obj = magic_function(obj)
obj.attr_one = 'new value'
obj.attr_two = 2
and it saves old values so i can get like this
print obj.old_attr_one
None
print obj.attr_one 'new value'
and
print obj.old_attr_two
1
print obj.attr_two
2
Something like this.. I wonder how can i do this by not touching the class of instance?
This is a start:
This isn’t bullet-proof when you’re trying to wrap weird objects (very little in Python is), but it should work for “normal” classes. You could write a lot more code to get a little bit closer to fully cloning the behaviour of the wrapped object, but it’s probably impossible to do perfectly. The main thing to be aware of here is that many special methods will not be redirected to the wrapped object.
If you want to do this without wrapping
objin some way, it’s going to get messy. Here’s an option:Note that this is extremely invasive if you’re using it on externally provided objects. It globally modifies the class of the object you’re applying the magic to, not just that one instance. This is because like several other special methods,
__setattr__is not looked up in the instance’s attribute dictionary; the lookup skips straight to the class, so there’s no way to just override__setattr__on the instance. I would characterise this sort of code as a bizarre hack if I encountered it in the wild (it’s “nifty cleverness” if I write it myself, of course 😉 ).This version may or may not play nicely with objects that already play tricks with
__setattr__and__getattr__/__getattribute__. If you end up modifying the same class several times, I think this still works, but you end up with an ever-increasing number of wrapped__setattr__definitions. You should probably try to avoid that; maybe by setting a “secret flag” on the class and checking for it inadd_old_setattr_to_classbefore modifyingcls. You should probably also use a more-unlikely prefix than justold_, since you’re essentially trying to create a whole separate namespace.