check if object is number

Steven Bethard steven.bethard at gmail.com
Fri Feb 11 14:11:44 EST 2005


Is there a good way to determine if an object is a numeric type? 
Generally, I avoid type-checks in favor of try/except blocks, but I'm 
not sure what to do in this case:

     def f(i):
         ...
         if x < i:
             ...

The problem is, no error will be thrown if 'i' is, say, a string:

py> 1 < 'a'
True
py> 10000000000 < 'a'
True

But for my code, passing a string is bad, so I'd like to provide an 
appropriate error.

I thought about calling int() on the value, but this will also allow 
some strings (e.g. '1').  I guess this isn't horrible, but it seems 
somewhat suboptimal...

Ideas?

Steve



More information about the Python-list mailing list