Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As others have answered, there could be other numeric types besides the ones you mention. One approach would be to check explicitly for the capabilities you want, with something like</p> <pre><code># Python 2 def is_numeric(obj): attrs = ['__add__', '__sub__', '__mul__', '__div__', '__pow__'] return all(hasattr(obj, attr) for attr in attrs) # Python 3 def is_numeric(obj): attrs = ['__add__', '__sub__', '__mul__', '__truediv__', '__pow__'] return all(hasattr(obj, attr) for attr in attrs) </code></pre> <p>This works for all your examples except the last one, <code>numpy.array(['1'])</code>. That's because <code>numpy.ndarray</code> has the special methods for numeric operations but raises TypeError if you try to use them inappropriately with string or object arrays. You could add an explicit check for this like</p> <pre><code> ... and not (isinstance(obj, ndarray) and obj.dtype.kind in 'OSU') </code></pre> <p>This may be good enough. </p> <p>But... you can never be <em>100%</em> sure that somebody won't define another type with the same behavior, so a more foolproof way is to actually try to do a calculation and catch the exception, something like</p> <pre><code>def is_numeric_paranoid(obj): try: obj+obj, obj-obj, obj*obj, obj**obj, obj/obj except ZeroDivisionError: return True except Exception: return False else: return True </code></pre> <p>but depending on how often you plan to call use it and with what arguments, this may not be practical (it can be potentially slow, e.g. with large arrays).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload