Skip to content Skip to sidebar Skip to footer

Causes For Inconsistent Behavior When Adding Nans To A Set

There is puzzling (at least for me) behavior of Python's set in combination with NaNs (here live): >>> float('nan') in {float('nan')} # example 1 False >>> nan

Solution 1:

set membership does an identity check as a short-circuit before considering an equality check (CPython source is in setobject.c, see also the note below PyObject_RichCompareBool).

Python core devs are motivated by these invariants:

for a in container:
    assert a in container    # this should ALWAYS be true

Ergo:

assert a in [a]
assert a in (a,)
assert a in {a}

It was decided that ensuring these invariants was the most important priority, and as for NaN: oh well. Special cases aren't special enough to break the rules. For all the gory details, see bpo issue4296:

Python assumes identity implies equivalence; contradicts NaN.

Post a Comment for "Causes For Inconsistent Behavior When Adding Nans To A Set"