Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #109746

Re: UserList - which methods needs to be overriden?

From Nagy László Zsolt <gandalf@shopzeus.com>
Newsgroups comp.lang.python
Subject Re: UserList - which methods needs to be overriden?
Date 2016-06-09 15:33 +0200
Message-ID <mailman.113.1465479217.2306.python-list@python.org> (permalink)
References <b245d88e-9b90-bb90-bd2a-13ee82f7a5c8@shopzeus.com> <njbdhk$pv2$1@ger.gmane.org> <917ca9c4-aef1-6681-ec70-62de8916117d@shopzeus.com> <njbp5d$mn9$1@ger.gmane.org> <7cdb398f-b3f2-9a3c-b444-2229f8496e2f@shopzeus.com>

Show all headers | View raw


> Using the built-in list or dict is problematic because sometimes the 
> subclass methods are ignored when the internal data is accessed (sorry, I 
> don't have an example).
Are you suggesting that I should use UserList and UserDict instead of
list and dict? What is the truth? Was UserDict left in collections for
backward compatibility, or not?

>
> How detailed is your change notification? If it's always the same method 
> invocation you may be able to create wrappers like
>
> def whatever(self, *args):
>     try:
>         return super().whatever(*args)
>     finally:
>         self.changed()
>
> automatically, and the base class, be it list or UserList or whatever 
> becomes a detail that can be chosen on a case by case basis.
My actual solution looks like this:


class ObservableCollection(Observable):
    @contextmanager
    def notify(self):
        self.notify_observers(EVT_BEFORE_COLLECTION_CHANGED)
        yield
        self.notify_observers(EVT_AFTER_COLLECTION_CHANGED)

class ObservableList(ObservableCollection, list):
    __slots__ = []

    def remove(self, value):
        with self.notify(): super().remove(value)

    def clear(self):
        with self.notify(): super().clear()

    def pop(self):
        with self.notify(): return super().pop()

It seems to be working with the built in list, dict and set types.

There must be a better way! Something like this:

@wrap_notify('remove', 'clear', 'append', 'insert', 'sort'):
class ObservableList(ObservableCollection, list):
    pass

I just can't find out the right syntax.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: UserList - which methods needs to be overriden? Nagy László Zsolt <gandalf@shopzeus.com> - 2016-06-09 15:33 +0200

csiph-web