norio norio - 3 months ago 7
Python Question

Python: how to check a variable is a meaningful numerical type

In python, how can I check a variable is a numerical type and has a meaningful value?

Here I mean by 'numerical type' those like

int
,
float
, and
complex
with all different bit length, and by 'meaningful value' that it is not
nan
or any other special values that can not be used for further computation.

(I guess this is such a common issue and there must be a duplicate question, but I did not find one after a quick search. Please let me know if there is a duplicate.)

Answer

Python 2.x only:

import math

def is_numerical(x):
    return isinstance(x, (int, long, complex, float)) and not math.isnan(x)

Python 2.x and 3.x:

import math
import sys

if sys.version_info >= (3, 0, 0):
    NUMERIC_TYPES = (int, complex, float)
else:
    NUMERIC_TYPES = (int, long, complex, float)

def is_numerical(x):
    return isinstance(x, NUMERIC_TYPES) and not math.isnan(x)

Reason for the distinction is because Python 3 merged the long and int types into just int.