class Something:
def __init__(self,x,y):
self.x = x
self.y = y
self.z = set()
def __hash__(self):
return hash((self.x, self.y, self.z))
def __eq__(self,other):
if not isinstance(other, Something):
return NotImplemented
return self.x == other.x and self.y == other.y
The above is the class definition. Inside main:
blah = []
for i in range(5):
blah.append(Something(i,i+1))
blah[0].z.add(blah[1])
For this, I get the TypeError: unhashable type: 'set'
error. One solution I found here was to make z a frozenset()
but that gives AttributeError: 'frozenset' object has no attribute 'add'
.
Any suggestions?
You should omit self.z
from your __hash__
method.
Since your __eq__
method ignores self.z
, it would be incorrect for __hash__
to take account of it anyway. And it solves the issue of self.z
being an unhashable (and mutable) type.