Re: Python __hash__ return value - what use is it?
[email protected] (Stefan Ram) 31 May 2026 09:40:07 GMT
| Newsgroups | comp.lang.python |
|---|---|
| Organization | Stefan Ram |
| Message-ID | <[email protected]> |
Veek M <[email protected]> wrote or quoted: >the instances into a set. However when I print the set I see individual >instances though I want the instances to be the treated the same .ie there >should be just one instance in the set because the return value from >__hash__ is always 1. I used the code below, where I added statements to print lengths, and all lengths printed are always "1" for me. Python Code #!/usr/bin/python class MyClass: def __bool__(self): print('in __bool__') return True def __hash__(self): # hash value is not a key print('in __hash__') return 1 def __eq__(self, val): print('in __eq__', val) return True c = MyClass() d = MyClass() if c: print("true") print('-----') s = set() s.add(c); print( "len( s )= ", len( s )) s.add(d); print( "len( s )= ", len( s )) print(s) print('-----') d = { c : "10", d : "20" } print( "len( d )= ", len( d )) print(d) Python Output (abbreviated at "...") in __bool__ true ----- in __hash__ len( s )= 1 in __hash__ in __eq__ <__main__.MyClass object at ...> len( s )= 1 {<__main__.MyClass object at ...>} ----- in __hash__ in __hash__ in __eq__ <__main__.MyClass object at ...> len( d )= 1 {<__main__.MyClass object at ...>: '20'}