0

I'm trying to find a way how to compare objects in sets to make & operator work properly on them.

I was trying to find source codes to Set function intersect(), but hopelessly. I have tried to overload the equals operator, but when I added __eq__() function into the class definition, the Person objects became unhashable.

class Person:
    def __init__(self, dictionary):
        self.dictionary = dictionary

def foo1():
    first_set.add(Person({"age" : 20}))

def foo2():
    second_set.add(Person({"age" : 20}))

first_set = set()
second_set = set()

foo1()
foo2()

print(first_set)
print(second_set)
print(first_set & second_set)  # I'd like to get non-empty intersection here

I thought it could work somehow with __eq__() overloading, but it's not possible.

Marek
  • 3
  • 2
  • Use ABC Set class and override `__eq__` method, https://docs.python.org/3/library/collections.abc.html#collections.abc.Set – iRhonin Apr 27 '19 at 13:10

1 Answers1

0

To make your classes collection safe like this, you need to override both __eq__ and __hash__ - see https://hynek.me/articles/hashes-and-equality/ and Recommended way to implement __eq__ and __hash__.

brunns
  • 2,689
  • 1
  • 13
  • 24
  • 2
    Of course, dictionaries (being mutable) aren't safely hashable. – chepner Apr 27 '19 at 13:12
  • True - you'd need some kind of [frozendict](https://stackoverflow.com/questions/39440190/a-workaround-for-pythons-missing-frozen-dict-type). – brunns Apr 27 '19 at 13:39