[Python-ideas] Consider adding clip or clamp function to math

Steven D'Aprano steve at pearwood.info
Thu Aug 4 21:21:45 EDT 2016


On Thu, Aug 04, 2016 at 11:12:36PM +1000, Chris Angelico wrote:
> On Thu, Aug 4, 2016 at 10:42 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> > I would like to see a common "isnan" function or method for both floats
> > and Decimal, because I'm sick of writing code like:
> >
> > try:
> >     flag = x.is_nan()  # Decimal?
> > except AttributeError:
> >     flag = math.isnan(x)  # float
> >
> >
> > Note that the spelling is different too, for extra sadness :-(
> 
> def isnan(x):
>     return x != x
> 
> Might land you a few false positives, but not many. And it's IEEE compliant.

That's what I used to use before math.isnan existed.

But I fear some clever clogs deciding that they like NANs but don't like 
that NANs violate reflexivity, or merely optimizing equality like this:

    def __eq__(self, other):
        # optimisation
        if self is other: return True
        # more expensive comparison
        ...

In the absence of an isnan() method or function, falling back on x!=x is 
okay as a last resort, but I wouldn't want to rely on it as the first 
resort.




-- 
Steve


More information about the Python-ideas mailing list