[Zope] Checking for an Integer Argument

Paul Winkler pw_lists at slinkp.com
Thu Jun 30 17:53:10 EDT 2005


On Thu, Jun 30, 2005 at 05:04:31PM -0400, Asad Habib wrote:
> Is there any way to check if an argument is an integer in Python?
> Offcourse, there is the int function but it chokes when passed an argument
> that is not a string and then the user is inconvenienced (it throws a
> ValueError to be specific). 

Well, to be precise, int() accepts strings as long as they can sensibly be
converted to integers, but it also accepts integers and floats.
For floats, it truncates them.  For other strings, it raises
a ValueError. For everything else, it raises a TypeError.

> I guess I could check each digit of the
> integer to determine if its ASCII value falls within the appropriate range
> and if each digit passed this test, then the entire number would be an
> integer.  Does anyone know of a simpler way that involves use of a
> predefined Python function? Likewise, does anyone know if a similar
> function exists to detect floating point numbers? Any help would be
> appreciated. Thanks.

It sounds to me like you don't want to know if an argument "is an integer",
but rather if an argument is a string that "looks like" an integer.
I interpret this as: Can this object be converted to an integer
without problems and without losing information?

Something like this might do, depending on how you want it
to handle floats such as 1.0:

>>> def looks_like_int(n):
...     try:
...         int(str(a))
...         return True
...     except (TypeError, ValueError):
...         return False
... 
>>> looks_like_int(1)
True
>>> looks_like_int("1")
True
>>> looks_like_int(1.0)
False
>>> looks_like_int("1.0")
False
>>> looks_like_int(1.3)
False
>>> looks_like_int("1.3")
False
>>> looks_like_int(None)
False
>>> looks_like_int("abc")
False

-- 

Paul Winkler
http://www.slinkp.com


More information about the Zope mailing list