[Python-Dev] collections.idset and collections.iddict?

Ian Bicking ianb at colorstudy.com
Tue Mar 7 07:04:45 CET 2006


Guido van Rossum wrote:
> On 3/6/06, Raymond Hettinger <python at rcn.com> wrote:
>> [Neil Schemenauer]
>>> I occasionally need dictionaries or sets that use object identity
>>> rather than __hash__ to store items.  Would it be appropriate to add
>>> these to the collections module?
>> Why not decorate the objects with a class adding a method:
>>    def __hash__(self):
>>        return id(self)
>>
>> That would seem to be more Pythonic than creating custom variants of other
>> containers.
> 
> I hate to second-guess the OP, but you'd have to override __eq__ too,
> and probably __ne__ and __cmp__ just to be sure. And probably that
> wouldn't do -- since the default __hash__ and __eq__ have the desired
> behavior, the OP is apparently talking about objects that override
> these operations to do something meaningful; overriding them back
> presumably breaks other functionality.
> 
> I wonder if this use case and the frequently requested
> case-insensitive dict don't have some kind of generalization in common
> -- perhaps a dict that takes a key function a la list.sort()?

That's what occurred to me as soon as I read Neil's post as well.  I 
think it would have the added benefit that it would be case insensitive 
while still preserving case.  Here's a rough idea of the semantics:

from UserDict import DictMixin

class KeyedDict(DictMixin):

     def __init__(self, keyfunc):
         self.keyfunc = keyfunc
         self.data = {}

     def __getitem__(self, key):
         return self.data[self.keyfunc(key)][1]

     def __setitem__(self, key, value):
         self.data[self.keyfunc(key)] = (key, value)

     def __delitem__(self, key):
         del self.data[self.keyfunc(key)]

     def keys(self):
         return [v[0] for v in self.data.values()]


I definitely like this more than a key-normalizing dictionary -- the 
normalized key is never actually exposed anywhere.  I didn't follow the 
defaultdict thing through to the end, so I didn't catch what the 
constructor was going to look like for that; but I assume those choices 
will apply here as well.

-- 
Ian Bicking  |  ianb at colorstudy.com  |  http://blog.ianbicking.org


More information about the Python-Dev mailing list