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>I am answering to my own question. This is based on <a href="http://stackoverflow.com/a/39396169/883431">Seth Michael Larson's answer</a>
and <a href="http://stackoverflow.com/a/12588878/883431">DaveTheScientist's answer for another question</a>. Considering that I need to be careful for <code>float('inf')</code> and <code>float('-inf')</code> as well as <code>float('nan')</code>, and that the passed argument <code>x</code> may be complex, I ended up writing the following function for the check.</p>

<pre><code>def is_a_meaningful_number(x):
    import math
    if sys.version_info &gt;= (3, 0, 0):
        NUMERIC_TYPES = (int, complex, float)
    else:
        NUMERIC_TYPES = (int, long, complex, float)
    return isinstance(x, NUMERIC_TYPES) and float('-inf') &lt; abs(x) &lt; float('inf')
</code></pre>

python numpy math