Steven Bethard wrote:Is there a good way to determine if an object is a numeric type?
Maybe this can help?
def isnumber(x): try: return(x == x-0) except: return False
Not exactly foolproof:
>>> def isnumber(x): ... try: return (x == x-0) ... except: return False ... >>> import numarray >>> a = numarray.arange(1.1, 5.5) >>> a array([ 1.1, 2.1, 3.1, 4.1, 5.1]) >>> print '%s:\t' % a, isnumber(a) [ 1.1 2.1 3.1 4.1 5.1]: [1 1 1 1 1]
The result is actually this:
>>> a == a-0 array([1, 1, 1, 1, 1], type=Bool)
And if you try to call bool() on it (as perhaps your isnumber() routine already should have, rather than relying on == to return a boolean):
>>> bool(a == (a-0))
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "C:\a\python24\Lib\site-packages\numarray\generic.py", line 477, in __nonzero__
raise RuntimeError("An array doesn't make sense as a truth value. Use sometrue(a) or alltrue(a).")
RuntimeError: An array doesn't make sense as a truth value. Use sometrue(a) or
alltrue(a).
Yuck.
Of course, most of the other definitions of "is a number" that have been posted may likewise fail (defined as not doing what the OP would have wanted, in this case) with a numarray arange. Or maybe not. (Pretty much all of them will call an arange a number... would the OP's function work properly with that?)
-Peter -- http://mail.python.org/mailman/listinfo/python-list