isNumber? check
Jeff Epler
jepler at unpythonic.net
Mon Sep 29 11:26:55 EDT 2003
First, whatever test you use, you should probably encapsulate it in a
function, so that if you need to update the definition you can do it at
one site instead of many:
def isnumeric(x):
return isinstance(x, (int, long, float))
You could have a registry of numeric types:
_numeric_types = ()
def register_numeric_type(t):
global _numeric_types
if t in _numeric_types: return
_numeric_types += (t,)
for value in (0, 0., 0l, 0j):
register_numeric_type(type(value))
def isnumeric(x):
return isinstance(x, _numeric_types)
Now, if someone wants to write a vector type, it merely needs to be
registered.
You could test that common numeric operations work:
def isnumeric(x):
try:
if x*1 == x and x+0 == x:
return 1
except TypeError:
pass
return 0
You could just run your code and let the eventual TypeError speak for
itself.. instead of
def f(x):
if not isnumeric(x): raise TypeError, "can't f() a %s" % type(x)
return x*x
just write
def f2(x):
return x*x
The difference in the quality of the error message is not large:
>>> f("")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in f
TypeError: can't f() a <type 'str'>
>>> f2("")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in f2
TypeError: unsupported operand type(s) for *: 'str' and 'str'
Jeff
More information about the Python-list
mailing list