[Zope] Python Function to Test for Integer Type

Alec Mitchell apm13 at columbia.edu
Tue Jun 15 19:45:10 EDT 2004


On Tuesday 15 June 2004 04:29 pm, Terry Hancock wrote:
> On Tuesday 15 June 2004 01:00 pm, Asad Habib wrote:
> > Hello. Does anyone know of a python function that returns a value based
> > on whether or not its argument is an integer? Any help would be greatly
> > appreciated. Thanks.
>
> if int(spam)==spam:
>     print "Yep, it's an integer."
>
> Technically this would accept "1.0000" as well as "1", but it's
> unclear to me why you would care about the actual storage format
> versus the meaning.  It won't accept '1', though, which might
> matter if spam comes from a web form.

For this to work properly, you'd want to catch exceptions on the int call 
(which would happen for '1.00' among other less sensible values).  If data 
were coming from the web and I wanted to convert sensible int-like values to 
ints, and accept things like 1.00 and '1.00', I might do:

try:
  if int(float(spam)) == float(spam):
    spam == int(float(spam))
    return "If it wasn't an integer before, it is now."
  else:
    return "That's not an integer, it's a float!"
except ValueError, TypeError:
    return "That's nothing like an integer!"

But that is certainly overkill if you really want to just check for the python 
type integer.

Good luck,
Alec Mitchell



More information about the Zope mailing list