Personally I still like the fundamental:

 

def is_nan(num):

    “”” Test for NaN “””

    return num != num

 

So simple!

 

From: Christopher Barker <pythonchb@gmail.com>
Sent: 28 December 2019 07:54
To: guido@python.org
Cc: python-ideas <python-ideas@python.org>
Subject: [Python-ideas] Re: Testing for NANs [was Re: Fix statistics.median()?]

 

opps, forgot to include my test code -- could be handy:

 

 

 

On Fri, Dec 27, 2019 at 11:52 PM Christopher Barker <pythonchb@gmail.com> wrote:

On Fri, Dec 27, 2019 at 5:39 PM Guido van Rossum <guido@python.org> wrote:

Is duck typing float or Decimal worth the bother? Barring that it could be done with some isinstance() checks (in the user code, not in math.isnan()).

 

well, for the topic at hand in another thread -- in the statistics module. And I was coming to the same conclusion, but it dawned on me that another option would be to add a .is_nan() method to floats. (same as Decimal). It would be a lighter-weight option that a new dunder, but accomplish a similar effect -- anyone implementing a new numeric type that support NaN could add that method.

 

BTW, could you simply do:

 

def is_nan(num):
    try:
        return num.is_nan()
    except AttributeError:
        if isinstance(num, complex):
            return cmath.isnan(num)
        try:
            return math.isnan(num)
        except:
            return False

 

I don't like the bare except, but it may be OK to say that anything that can't be coerced to a float is not a NaN. (na you could trap the exeptions we expect anyway)

 

And this doesn't require you to import the Decimal module, and you can document that it will work with any type that either has an is_nan() method, or can have its NaN values successfully coerced into a float.

 

And we could remove the complex support -- does the rest of the statistics module support it anyway? But it did make me think -- what if the complex number __float__() would work for NaN, and Inf, and -inf -- then you could have a single isnan() implementation in the math module, 

 

(in fact, that could be a standard part of the __float__ protocol)

 

 

By the way:

 

----> 1 float(Decimal('snan'))
ValueError: cannot convert signaling NaN to float

 

Why can't it convert a signaling NaN to a float? Isn't a signaling NaN part of the IEE 754 spec?

 

-CHB

 

--

Christopher Barker, PhD

Python Language Consulting
  - Teaching
  - Scientific Software Development
  - Desktop GUI and Web Development
  - wxPython, numpy, scipy, Cython


 

--

Christopher Barker, PhD

Python Language Consulting
  - Teaching
  - Scientific Software Development
  - Desktop GUI and Web Development
  - wxPython, numpy, scipy, Cython