Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #109764
| From | Michael Selik <michael.selik@gmail.com> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: UserList - which methods needs to be overriden? |
| Date | 2016-06-09 22:38 +0000 |
| Message-ID | <mailman.125.1465511920.2306.python-list@python.org> (permalink) |
| References | <b245d88e-9b90-bb90-bd2a-13ee82f7a5c8@shopzeus.com> <CAGgTfkMakty7MohzRwLPpfRJikKBC0osTE83T0hZ9Scn+1NBOA@mail.gmail.com> |
On Thu, Jun 9, 2016 at 5:07 AM Nagy László Zsolt <gandalf@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)
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: UserList - which methods needs to be overriden? Michael Selik <michael.selik@gmail.com> - 2016-06-09 22:38 +0000
csiph-web