Lookup table for unhashable in Python

后端 未结 4 1678
粉色の甜心
粉色の甜心 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 19:52

    Mappings with mutable objects as keys are generally difficult. Is that really what you want? If you consider your objects to be immutable (there is no way to really enforce immutability in Python), or you know they will not be changed while they are used as keys in a mapping, you can implement your own hash-function for them in several ways. For instance, if your object only has hashable data-members, you can return the hash of a tuple of all data-members as the objects hash.

    If your object is a dict-like, you can use the hash of a frozenset of all key-value-pairs.

    def __hash__(self):
        return hash(frozenset(self.iteritems()))
    

    This only works if all values are hashable. In order to save recalculations of the hashes (which would be done on every lookup), you can cache the hash-value and just recalculate it if some dirty-flag is set.

提交回复
热议问题