John Machin wrote:
OK, I'll rephrase: what is your interest in DictMixin?

My interest: I'm into mappings that provide an approximate match
capability, and have a few different data structures that I'd like to
implement as C types in a unified manner. The plot includes a base type
that, similarly to DictMixin, provides all the non-basic methods.

I was recently trying to prototype a simple mapping type that implements the suggestion "Improved default value logic for Dictionaries" from
http://www.python.org/moin/Python3_2e0Suggestions
You can't just inherit from dict and override dict.__getitem__ because dict.__getitem__ isn't always called:


py> class D(dict):
...     def __init__(*args, **kwds):
...         self = args[0]
...         self.function, self.args, self.kwds = None, None, None
...         super(D, self).__init__(*args[1:], **kwds)
...     def setdefault(self, function, *args, **kwds):
...         self.function, self.args, self.kwds = function, args, kwds
...     def __getitem__(self, key):
...         if key not in self:
...             super(D, self).__setitem__(
...                 key, self.function(*self.args, **self.kwds))
...         return super(D, self).__getitem__(key)
...
py> d = D()
py> d.setdefault(list)
py> d['c'].append(2)
py> d
{'c': [2]}
py> print d.get('d') # should print []
None

This, of course, is exactly the kind of thing that DictMixin is designed for. =)

Of course, it's no trouble for me to implement keys(). I was just wondering why that design decision was made when it seems like __iter__ is more integral to the mapping protocol. And if you want efficient iteration over your mapping type, you're going to have to define __iter__ too...

Steve
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to