Hook into adding / removing items from list in python
I'd like to create a drop-in replacement for python's list
, that will allow me to know when an item is added or removed. A subclass of list, or something that implements the list interface will do equally well. I'd prefer a solution where I don't have to reimplement all of list's functionality though. Is there a easy + pythonic way to do it?
Pseudocode:
class MyList(list):
# ...
def on_add(self, items):
print "Added:"
for i in items:
print i
# and the same for on_remove
l =开发者_如何学运维 MyList()
l += [1,2,3]
# etc.
To see what functions are defined in list, you can do
>>> dir(list)
Then you will see what you can override, try for instance this:
class MyList(list):
def __iadd__(self, *arg, **kwargs):
print "Adding"
return list.__iadd__(self, *arg, **kwargs)
You probably need to do a few more of them to get all of it.
The documentation for userlist tells you to subclass list
if you don't require your code to work with Python <2.2. You probably don't get around overriding at least the methods which allow to add/remove elements. Beware, this includes the slicing operators.
精彩评论