I need to design object that support some sort of uncertainty (or wild characters, if you wish) it its components.
The work is done in Python.
Consider the following class
class C():
def __init__(self, p1):
self.p1 = p1
The property p1 can be either “x”, “y”, “z”, but sometimes “x or y”, or any other combination.
It is required that if p1 of c1 is ‘x’ and p1 of c2 is ‘x or y’, then c1 == c2 will return True. This is easily achieved by supplying a proper __eq__ function.
However, these objects need also to be stored in sets, therefore I need to supply a __hash__ function.
How would you calculate hash function for this case, such if c1 == c2 then hash(c1) == hash(c2)?
Option 1: hashing the property
Not good Here’s why
c1 = C('x')
c2 = C('x or y or z')
c1 == c2 #True
hash(c1) == hash(c2)#False
Your equality criterion is not transitive, and therefore invalid:
but
Since you can construct an element that equals all others
C('x or y or z or a or ...'), the only hash function that fulfills c1 == c2 ⇒ hash(c1) == hash(c2) is a constant one, i.e.