norio - 1 year ago 91

Python Question

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`

`complex`

`nan`

(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 Source

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`

.