check if object is number

Fredrik Lundh fredrik at pythonware.com
Fri Feb 11 14:58:39 EST 2005


Steven Bethard wrote:

> 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.

assert operator.isNumberType(i)

(but make sure you read the warning in the docs:
http://docs.python.org/lib/module-operator.html )

</F> 






More information about the Python-list mailing list