How to test if object is an integer?

Roy Smith roy at panix.com
Mon Oct 17 20:33:08 EDT 2011


In article <mailman.2051.1318881724.27778.python-list at python.org>,
 Mathias Lafeldt <mathias.lafeldt at googlemail.com> wrote:

> According to [1], there're more Exceptions to test for:
> 
> try:
>     int(s)
>     return True
> except (TypeError, ValueError, OverflowError): # int conversion failed
>     return False


I don't think I would catch TypeError here.  It kind of depends on how 
isInt() is defined.  Is it:

def isInt(s):
  "Return True if s is a string representing an integer"

or is it:

def isInt(s):
  "Return True if s (which must be a string) represents an integer"

If the latter, then passing a non-string violates the contract, and the 
function should raise TypeError.  If the former, then you could make 
some argument for catching the TypeError and returning False, but I 
think the second version is what most people have in mind for isInt().

Can you even get an OverflowError any more in a modern Python?

>>> 
int('99999999999999999999999999999999999999999999999999999999999999999')
99999999999999999999999999999999999999999999999999999999999999999L



More information about the Python-list mailing list