Planning a Python Course for Beginners
Python
python at example.invalid
Thu Aug 10 12:02:50 EDT 2017
Marko Rauhamaa wrote:
> Python <python at example.invalid>:
>
>> Marko Rauhamaa wrote:
>>> Python <python at example.invalid>:
>>>
>>>> Marko Rauhamaa wrote:
>>>>> id() is actually an ideal return value of __hash__(). The only criterion
>>>>> is that the returned number should be different if the __eq__() is
>>>>> False. That is definitely true for id().
>>>>
>>>> $ python
>>>> Python 2.7.13 (default, Jan 19 2017, 14:48:08)
>>>> [GCC 6.3.0 20170118] on linux2
>>>> Type "help", "copyright", "credits" or "license" for more information.
>>>>>>> nan = float('NaN')
>>>>>>> id(nan) == id(nan)
>>>> True
>>>>>>> nan == nan
>>>> False
>>>>>>>
>>>
>>> Point being?
>>
>> It is a counter example to your claim that if __eq__(...) is false
>> then id should return different values.
>
> No it's not:
>
> * __hash__() *should* return different values. It is neither possible
> nor necessary in the general case.
>
> * For NaN, there's no better alternative.
>
> * Dictionaries and sets try "is" before __eq__(...) so everything works
> anyway.
>
>
> So, to be precise, the __hash__() rule is:
>
> a.__hash__() *should* return a different number than b.__hash__() if
> a is not b and not a.__eq__(b)
>
> a.__hash__() *must* return the same number as b.__hash__() if
> a is b or a.__eq__(b)
I didn't disagree with any of these statements about __hash__, but only
your statement about id and __eq__:
> id() is actually an ideal return value of __hash__(). The only criterion
> is that the returned number should be different if the __eq__() is
> False. That is definitely true for id()
nan is a clear, simple, undeniable counterexample to that claim.
the hash function for floats is quite interesting btw, you may want to
look what is its value for nan.
More information about the Python-list
mailing list