Skip to content
Advertisement

How should I implement __eq__ and __hash__ if I want order independent equality

I have a class with a field named arglist whose value is a list. I would like the order maintained to respect the callers provided order; however, I’d like equality to be independent of order.

I have implemented the __eq__ method as follows:

    def __eq__(self, that):
        return type(self) is type(that) and 
            set(self.arglist) == set(that.arglist)

How should I now implement the __hash__ method? When I try to the following, I get a runtime error.

    def __hash__(self):
        return hash(set(self.arglist))

The error I get is

  File "/Users/jnewton/Repos/python-rte/genus/src/s_member.py", line 55, in __hash__
    return hash(set(self.arglist))
TypeError: unhashable type: 'set'

Maybe what I’m trying to do doesn’t really make sense? Do I need to give up on the idea of order-independent equality?

Advertisement

Answer

The hash() method in python only works with immutable data type but set is a mutable data type, hence it is throwing an error. A frozenset or tuple which are immutable could be used instead.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement