norio norio - 5 months ago 16
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

, and
with all different bit length, and by 'meaningful value' that it is not
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.)


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)
    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.