On Fri, Dec 27, 2019 at 5:39 PM Guido van Rossum <gu...@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
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/5SE7D67ETPQ3Q46GUG2ZQO5MVS42YF5L/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to