Skip to content

Instantly share code, notes, and snippets.

@mahenzon
Created March 16, 2026 20:19
Show Gist options
  • Select an option

  • Save mahenzon/84d0d8d0d879a4c147f36e60214d9ecb to your computer and use it in GitHub Desktop.

Select an option

Save mahenzon/84d0d8d0d879a4c147f36e60214d9ecb to your computer and use it in GitHub Desktop.
Python set add same hash value item if no eq
class A:
def __init__(self, val):
self.val = val
def __hash__(self):
return hash(self.val)
def __str__(self):
return str(self.val)
def __repr__(self):
return str(self)
class B:
def __init__(self, val):
self.val = val
def __hash__(self):
return hash(self.val)
def __eq__(self, other): # important!
return isinstance(other, self.__class__) and self.val == other.val
def __str__(self):
return str(self.val)
def __repr__(self):
return str(self)
a1 = A(42)
a2 = A(42)
print({a1, a2})
# {42, 42}
b1 = B(52)
b2 = B(52)
print({b1, b2})
# {52}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment