How to test if object is an integer?

M

MrPink

Is there a function in Python that can be used to test if the value in
a string is an integer? I had to make one up for myself and it looks
like this:

def isInt(s):
try:
i = int(s)
return True
except ValueError:
return False
 
C

Chris Angelico

Is there a function in Python that can be used to test if the value in
a string is an integer?  I had to make one up for myself and it looks
like this:

def isInt(s):
   try:
       i = int(s)
       return True
   except ValueError:
       return False

There's some ambiguity in the definition of "is an integer". For
instance, is "0x100" an integer? Is "0800"? If your definition of "is
an integer" is "can be passed to int() without triggering an
exception" (which is probably the most useful), then your above code
is about perfect. The only change I'd make is to not have an isInt
function at all, but simply to try/except at the point where you need
to make the conversion.

ChrisA
 
M

Mathias Lafeldt

Is there a function in Python that can be used to test if the value in
a string is an integer?  I had to make one up for myself and it looks
like this:

def isInt(s):
   try:
       i = int(s)
       return True
   except ValueError:
       return False

According to [1], there're more Exceptions to test for:

try:
int(s)
return True
except (TypeError, ValueError, OverflowError): # int conversion failed
return False

[1] http://jaynes.colorado.edu/PythonIdioms.html, idiom "Catch errors
rather than avoiding them to avoid cluttering your code with special
cases"

-Mathias
 
N

Noah Hall

Is there a function in Python that can be used to test if the value in
a string is an integer?  I had to make one up for myself and it looks
like this:

def isInt(s):
   try:
       i = int(s)
       return True
   except ValueError:
       return False


There's the isdigit method, for example -
False
 
R

Roy Smith

Mathias Lafeldt said:
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
 
C

Chris Kaynor

Python 2.6 running on Windows 7:OverflowError: (34, 'Result too large')
Traceback (most recent call last):
  File "<stdin-inspect>", line 1, in <module>
OverflowError: (34, 'Result too large')

However, from the documentation:
"Because of the lack of standardization of floating point exception
handling in C, most floating point operations also aren’t checked."
(http://docs.python.org/library/exceptions.html#exceptions.OverflowError)

Chris

 Mathias Lafeldt said:
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
 
I

Ian Kelly

Python 2.6 running on Windows 7:
OverflowError: (34, 'Result too large')
Traceback (most recent call last):
  File "<stdin-inspect>", line 1, in <module>
OverflowError: (34, 'Result too large')

However, from the documentation:
"Because of the lack of standardization of floating point exception
handling in C, most floating point operations also aren’t checked."
(http://docs.python.org/library/exceptions.html#exceptions.OverflowError)

I think what Roy meant was "can you even get an OverflowError from
calling int() any more", to which I think the answer is no, since in
modern Pythons int() will auto-promote to a long, and in Python 3
they're even the same thing.
 
Y

Yingjie Lan

----- Original Message -----
From: Noah Hall <[email protected]>
To: MrPink <[email protected]>
Cc: (e-mail address removed)
Sent: Tuesday, October 18, 2011 4:44 AM
Subject: Re: How to test if object is an integer?
There's the isdigit method, for example -

False

There are some corner cases to be considered with this approach:
1. negative integers: '-3'
2. strings starting with '0': '03'
3. strings starting with one '+': '+3'
 
S

Steven D'Aprano

exceptions.html#exceptions.OverflowError)

I think what Roy meant was "can you even get an OverflowError from
calling int() any more", to which I think the answer is no, since in
modern Pythons int() will auto-promote to a long, and in Python 3
they're even the same thing.


You can still get an OverflowError:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: cannot convert float infinity to integer


and similarly for Decimal('inf') as well.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top