isNumber? check
Jean-S?bastien Bolduc
jseb at cs.mcgill.ca
Tue Sep 30 01:05:28 EDT 2003
> > How do I check if a value is a number in Python?
> >
> > One way is (x == type(1)) and (x == type(1.2)) and (x ==
> > type(2387482734274)) and ...
>
> Why do you want to do so? Maybe, it is better in your
> case to just run the piece of code using the number, and
> if it fails, it fails. However, if you must, you need to
> do type(x) is type(1) and ... etc., or isinstance(x, int)
> and isinstance(x, float), etc.
I used to use the latter approach suggested by Gerrit, but I recently
found on the web an alternative, elegant approach that might work
(sorry, I don't recall where I found it!):
hasattr(x, '__int__')
If the "__int__" method is defined for "x", it is a number. This will
work for integer, long, float and complex types, as well as for custom
classes that emulate numeric types.
Regards,
JSeb
More information about the Python-list
mailing list