How do I detect when something is added to a list? Is there an equivalent to the dictionary __setitem__
method, that will get called when something is added to the list by insert
, extend
, append
or using +
or +=
(__add__
, __iadd__
), or some other method that I probably forgot about? Or do I need to hook into each of those methods, one by one?
You'll need to override each method separately. Especially as the operations you've mentioned are different in nature - append
, insert
, extend
, and +=
modify the list in place while +
creates a new list.
If you're feeling fancy, this is a potential way to do it without having to write too much boilerplate:
class MyList(list):
pass
for method in ['append', 'insert', 'extend', '__add__', '__iadd__']:
def code_added(self, *args, **kwargs):
# Your code here
getattr(super(MyList, self), method)(*args, **kwargs)
setattr(MyList, method, code_added)
Depending on what the code you want to run accesses, you might need to handle __add__
separately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With