-1

I have a class MyClass where I have also overridden the __eq__ method for comparing two objects of the class as I want to, and I can do this:

obj1 = MyClass(a = 2)
obj2 = MyClass(a = 2)

obj1 == obj2 # gives me True

Now my problem is that I have two lists including objects of this class, and I want to compare whether or not the set of these two lists are the same. Such that I expect that:

list1 = [MyClass(a=1), MyClass(a=2)]
list2 = [MyClass(a=2), MyClass(a=1)]

set(list1) == set(list2)

gives me True. But I run into this error:

TypeError: unhashable type: 'MyClass'

which is clearly because of the set() line. How can I do this? (I don't care about using or not using set as long as I can compare two lists of objects compared regardless of their order.)

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Alireza
  • 656
  • 1
  • 6
  • 20

1 Answers1

1

Have a look at the python docs concerning what makes a class hashable. You will need to implement both __eq__ and __hash__. You will need to ensure that objects that are equal to one another also produce the same hash value.

TomMP
  • 715
  • 1
  • 5
  • 15