Check if a variable is nan with Python I want to check if a variable is nan with Python.

I have a working method value != value gives True if value is an nan. However, it is ugly and not so readable. Plus, sonarcloud considers it as a bug for the reason "identical expressions should not be used on both sides of a binary operator".

Do you have a better/elegant solution? Thanks.

import math
import numpy as np

v1 = float('nan')
v2 = math.nan
v3 = np.nan

def check_nan(value) -&gt; bool:
    is_nan =  value != value
    return is_nan

v1_is_nan = check_nan(value=v1)
v2_is_nan = check_nan(value=v2)
v3_is_nan = check_nan(value=v3)

print(v1_is_nan)  # printed True
print(v2_is_nan)  # printed True
print(v3_is_nan)  # printed True
Methods for this already exist, particularly because of the weird properties of NaNs. One of them can be found in the math library, math.isnan and numpy already has a method implemented for this as well, numpy.isnan. They both deal with all three kinds of NaNs shown in your code (but the numpy version is vectorized):

import math
import numpy as np

list(map(math.isnan, [float("nan"), math.nan, np.nan]))
# [True, True, True]

np.isnan([float("nan"), math.nan, np.nan]) 
# array([ True,  True,  True])


If you are using pandas, pandas.isna is also interesting because it considers None and pandas.NaT (Not a Time) as missing values as well:

import pandas as pd

pd.isna([float("nan"), math.nan, np.nan, None, pd.NaT])
# array([ True,  True,  True,  True,  True])




Your code has a potential flaw, it does not return True only for NaNs (although it does return True for all NaNs), but for all objects which are not equal to themselves. In particular, it will think any instance of this class is NaN (probably true, but not necessarily):

class A:
    def __equal__(self, other):
        return False