Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run code when an element is added to a list

Tags:

python

list

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?

like image 840
leo Avatar asked Feb 04 '23 05:02

leo


1 Answers

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.

like image 80
obskyr Avatar answered Feb 06 '23 19:02

obskyr