Is there any way to make a list call a function every time the list is modified?
For example:
>>>l = [1, 2, 3]
>>>def callback():
print "list changed"
>>>apply_callback(l, callback) # Possible?
>>>l.append(4)
list changed
>>>l[0] = 5
list changed
>>>l.pop(0)
list changed
5
Borrowing from the suggestion by @sr2222, here’s my attempt. (I’ll use a decorator without the syntactic sugar):
The great thing about this is if you realize you forgot to consider a particular method, it’s just 1 line of code to add it. (For example, I forgot
__iadd__and__imul__until just now 🙂EDIT
I’ve updated the code slightly to be py2k and py3k compatible. Additionally, slicing creates a new object of the same type as the parent. Please feel free to continue poking holes in this recipe so I can make it better. This actually seems like a pretty neat thing to have on hand …