[Python-Dev] decimal.py: == and != comparisons involving NaNs

Stefan Krah stefan-usenet at bytereef.org
Mon Nov 9 14:21:24 CET 2009


Antoine Pitrou <solipsis at pitrou.net> wrote:
> > I see the point, but Decimal("NaN") does not hash:
> 
> Ok but witness again:
> 
> >>> L = [1, 2, Decimal("NaN"), 3]
> >>> 3 in L
> True
> >>> class H(object):
> ...   def __eq__(self, other): raise ValueError
> ... 
> >>> L = [1, 2, H(), 3]
> >>> 3 in L
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 2, in __eq__
> ValueError


Yes, but the list is already broken in two ways:

>>> L.sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/decimal.py", line 877, in __lt__
    ans = self._compare_check_nans(other, context)
  File "/usr/lib/python2.7/decimal.py", line 782, in _compare_check_nans
    self)
  File "/usr/lib/python2.7/decimal.py", line 3755, in _raise_error
    raise error(explanation)
decimal.InvalidOperation: comparison involving NaN

>>> Decimal("NaN") in L
False



> (NB: interestingly, float("nan") does hash)


I wonder if it should:

>>> d = {float('nan'): 10, 0: 20}
>>> 0 in d
True
>>> float('nan') in d
False
>>> d[float('nan')]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: nan
>>> 


I guess my point is that NaNs in lists and dicts are broken in so many
ways that it might be good to discourage this use. (And get the added
benefit of safer mathematical behavior for == and !=.)


Stefan Krah





More information about the Python-Dev mailing list