it's really astounding to see such a heated discussion coming up when such a basic, valid and, i believe, mundane question is being asked.
some people have pointed out that type-checking against int
(and long
) might loose cases where a big decimal number is encountered. quite right.
some people have pointed out that you should 'just do x + 1
and see whether that fails. well, for one thing, this works on floats too, and, on the other hand, it's easy to construct a class that is definitely not very numeric, yet defines the +
operator in some way.
i am at odds with many posts vigorously declaring that you should not check for types. well, GvR once said something to the effect that in pure theory, that may be right, but in practice, isinstance
often serves a useful purpose (that's a while ago, don't have the link; you can read what GvR says about related issues in posts like this one).
what is funny is how many people seem to assume that the OP's intent was to check whether the type of a given x
is a numerical integer type—what i understood is what i normally mean when using the OP's words: whether x
represents an integer number. and this can be very important: like ask someone how many items they'd want to pick, you may want to check you get a non-negative integer number back. use cases like this abound.
it's also, in my opinion, important to see that (1) type checking is but ONE—and often quite coarse—measure of program correctness, because (2) it is often bounded values that make sense, and out-of-bounds values that make nonsense. sometimes just some intermittent values make sense—like considering all numbers, only those real (non-complex), integer numbers might be possible in a given case.
funny non-one seems to mention checking for x == math.floor( x )
. if that should give an error with some big decimal class, well, then maybe it's time to re-think OOP paradigms. there is also PEP 357 that considers how to use not-so-obviously-int
-but-certainly-integer-like values to be used as list indices. not sure whether i like the solution.