Python: how to check a variable is a meaningful numerical type
<p>In python, how can I check a variable is a numerical type and has a meaningful value? </p>

<p>Here I mean by 'numerical type' those like <code>int</code>, <code>float</code>, and <code>complex</code> with all different bit length, and by 'meaningful value' that it is not <code>nan</code> or any other special values that can not be used for further computation. </p>

<p>(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.)</p>

<p>Python 2.x and 3.x</p>

<pre><code>import math
import numbers

def is_numerical(x):
    return isinstance(x, numbers.Number) and not isinstance(x, bool) and not math.isnan(abs(n)) and math.isfinite(abs(n))
</code></pre>

<p>Reason for the distinction is because Python 3 merged the <code>long</code> and <code>int</code> types into just <code>int</code>.</p>

<p>Edit: Added upon answer below using <code>numbers.Number</code> to exclude booleans.</p>

python numpy math