Run code when item is added to list

How to determine when something is added to the list? Is there an equivalent method of the dictionary __setitem__, which will be called when something is added to the list using insert, extend, appendor by using +or +=( __add__, __iadd__) or some other method, which I must have forgotten? Or do I need to connect each of these methods one by one?

+4
source share
2 answers

You need to override each method separately. Especially because the operation you mentioned different in nature - append, insert, extendand +=change the list on the site, and +creates a new list.

If you feel like a fantasy, this is a potential way to do this without having to write too many templates:

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 code you want to run, you may need to process it __add__separately.

+4
source

as the obskyr answer suggests, you must define a child class listand override many methods and thoroughly test to see if you notice something.

, __getattribute__ ( ), __iadd__ ( +=) __setitem__ ( ), , :

class MyList(list):
    def __getattribute__(self,a):
        if a in {"append","extend","remove","insert","pop","reverse","sort","clear"}:
            print("modification by {}".format(a))
        else:
            print("not modified {}".format(a))
        return list.__getattribute__(self,a)

    def __iadd__(self,v):
        print("in place add")
        return list.__iadd__(self,v)

    def __setitem__(self,i,v):
        print("setitem {},{}".format(i,v))
        return list.__setitem__(self,i,v)

l = MyList()

l.append(12)
l.extend([12])
l.remove(12)
print(l)
l[:] = [4,5,6]
l += [5]
print(l)

:

modification by append
modification by extend
modification by remove
[12]
setitem slice(None, None, None),[4, 5, 6]
in place add
[4, 5, 6, 5]

, , .

+4

Source: https://habr.com/ru/post/1679868/


All Articles