Lookup table for unhashable in Python

后端 未结 4 1662
粉色の甜心
粉色の甜心 2021-01-12 19:45

I need to create a mapping from objects of my own custom class (derived from dict) to objects of another custom class. As I see it there are two ways of doing this:

4条回答
  •  温柔的废话
    2021-01-12 20:18

    Here is an implementation of a frozendict, taken from http://code.activestate.com/recipes/414283/:

    class frozendict(dict):
        def _blocked_attribute(obj):
            raise AttributeError, "A frozendict cannot be modified."
        _blocked_attribute = property(_blocked_attribute)
    
        __delitem__ = __setitem__ = clear = _blocked_attribute
        pop = popitem = setdefault = update = _blocked_attribute
    
        def __new__(cls, *args):
            new = dict.__new__(cls)
            dict.__init__(new, *args)
            return new
    
        def __init__(self, *args):
            pass
    
        def __hash__(self):
            try:
                return self._cached_hash
            except AttributeError:
                h = self._cached_hash = hash(tuple(sorted(self.items())))
                return h
    
        def __repr__(self):
            return "frozendict(%s)" % dict.__repr__(self)
    

    I would replace tuple(sorted(self.items())) by frozenset(self.iteritems()) as in Spacecowboy's answer. And consider adding __slots__ = ("_cached_hash",) to the class.

提交回复
热议问题