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:
JavaScript
x
4
1
def __eq__(self, that):
2
return type(self) is type(that) and
3
set(self.arglist) == set(that.arglist)
4
How should I now implement the __hash__
method? When I try to the following, I get a runtime error.
JavaScript
1
3
1
def __hash__(self):
2
return hash(set(self.arglist))
3
The error I get is
JavaScript
1
4
1
File "/Users/jnewton/Repos/python-rte/genus/src/s_member.py", line 55, in __hash__
2
return hash(set(self.arglist))
3
TypeError: unhashable type: 'set'
4
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.