UserList - which methods needs to be overriden?

Michael Selik michael.selik at gmail.com
Thu Jun 9 18:38:28 EDT 2016


On Thu, Jun 9, 2016 at 5:07 AM Nagy László Zsolt <gandalf at shopzeus.com>
wrote:

> I would like to create a collections.UserList subclass that can notify
> others when the list is mutated.
>

Why not subclass MutableSequence instead? The ABC will tell you which
methods to override (the abstract ones). The mixin methods rely on those
overrides.

    from collections.abc import MutableSequence

    def noisy(message):
        def decorator(func):
            def wrapper(*args, **kwargs):
                print(message)
                return func(*args, **kwargs)
            return wrapper
        return decorator

    class NoisyList(MutableSequence):
        def __init__(self, *args, **kwargs):
            self.contents = list(*args, **kwargs)

        def __getitem__(self, index):
            return self.contents[index]

        def __len__(self):
            return len(self.contents)

        @noisy('set')
        def __setitem__(self, index, value):
            self.contents[index] = value

        @noisy('del')
        def __delitem__(self, index):
            del self.contents[index]

        @noisy('insert')
        def insert(self, index, value):
            self.contents.insert(index, value)


More information about the Python-list mailing list