[Python-Dev] PyObject_RichCompareBool identity shortcut
Steven D'Aprano
steve at pearwood.info
Fri Apr 29 03:37:16 CEST 2011
Nick Coghlan wrote:
> 1. IEEE754 is a value-based system, with a finite number of distinct
> NaN payloads
> 2. Python is an object-based system. In addition to their payload, NaN
> objects are further distinguished by their identity (infinite in
> theory, in practice limited by available memory).
I argue that's an implementation detail that makes no difference. NANs
should compare unequal, including to itself. That's the clear intention
of IEEE-754. There's no exception made for "unless y is another name for
x". If there was, NANs would be reflexive, and we wouldn't be having
this discussion, but the non-reflexivity of NANs is intended behaviour.
The clear equivalent to object identity in value-languages is memory
location. If you compare variable x to the same x, IEEE754 says you
should get False.
Consider:
# Two distinct NANs are calculated somewhere...
x = float('nan')
y = float('nan')
# They find themselves in some data in some arbitrary place
seq = [1, 2, x, y]
random.shuffle(seq)
# And later x is compared to some arbitrary element in the data
if math.isnan(x):
if x == seq[0]:
print("Definitely not a NAN")
nan != x is an important invariant, breaking it just makes NANs more
complicated and less useful. Tests will need to be written "if x == y
and not math.isnan(x)" to avoid getting the wrong result for NANs.
I don't see what the problem is that we're trying to fix. If containers
wish to define container equality as taking identity into account, good
for the container. Document it and move on, but please don't touch floats.
--
Steven
More information about the Python-Dev
mailing list