check if object is number

George Sakkis gsakkis at rutgers.edu
Fri Feb 11 15:07:42 EST 2005


"Steven Bethard" <steven.bethard at gmail.com> wrote in message
news:gcidnb9g_ojxnpDfRVn-tA at comcast.com...
> 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

The thing is that python avoids giving a strict definition of what is a 'numeric type', i.e. a
well-defined interface (the same holds for other frequently used interfaces such as 'sequence',
'mapping', 'file-like', etc). It's up to you (the user) to think of all the operations you
anticipate to be supported by each argument, attribute, etc. and define a 'numeric type checker' (or
even better, adaptor) that suits *your application*. In your example, what does your application
consider to be numeric ? Strings are definitely not, integers and floats typically are; on the other
hand, complex numbers are usually not expected, even though mathematically they are 'numeric'.  In
this case, you can write something like:
    def isNumeric(obj):
        # consider only ints and floats numeric
        return isinstance(obj,int) or isinstance(obj,float)

The bottom line is that python wisely doesn't enforce any universal numeric type ("in the face of
ambiguity, refuse the temptation to guess").

George





More information about the Python-list mailing list