UserList - which methods needs to be overriden?
Nagy László Zsolt
gandalf at shopzeus.com
Thu Jun 9 09:33:32 EDT 2016
> 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.
More information about the Python-list
mailing list