checking if a number is int
Jim Dennis
jimd at vega.starshine.org
Sun Apr 7 16:32:58 EDT 2002
In article <MPG.17197f04a3f463e8989680 at news.planet.nl>, Johannes Gijsbers wrote:
>logistix wrote:
>> Use python's type system:
>> >>> import types
>> >>> a, b = 1, 1.0
>> >>> if type(a) == types.IntType: print "int"
>> ...
>> int
>> >>> if type(b) == types.IntType: print "int"
>> ...
>> >>>
>That's not really a good idea, as math.sqrt() returns a float. I'd say:
...
>Johannes Gijsbers
Worse, it doesn't account for subclasses of integer.
In Python it is considered poor form to check for types; it's
better to test for attributes or properties. So one might
take an anonymous object and do something like:
def deal_with_unknown(a)
if hasattr(a,'__mod__') and not a % 1:
....
... since we can reasonably assert that all subclasses of numbers
and integers should have (or inherit) an __mod__ (modulo) attribute.
This example should short circuit so that any non-number that's
passed to it will not raise an exception because a % 1 will be
skipped if hasattr() is false.
More information about the Python-list
mailing list