C api and checking for integers
casevh
casevh at gmail.com
Thu Nov 12 09:38:40 EST 2009
On Nov 12, 1:28 am, "lallous" <lall... at lgwm.org> wrote:
> Hello,
>
> I am a little confused on how to check if a python variable is an integer or
> not.
>
> Sometimes PyInt_Check() fails and PyLong_Check() succeeds.
I assume you are using Python 2.x. There are two integer types: (1)
PyInt which stores small values that can be stored in a single C long
and (2) PyLong which stores values that may or may not fit in a single
C long. The number 2 could arrive as either a PyInt or a PyLong.
Try something like the following:
if PyInt_CheckExact()
myvar = PyInt_AS_LONG()
else if PyLong_CheckExact()
myvar = PyLong_As_Long()
if ((myvar == -1) && (PyErr_Occurred())
# Too big to fit in a C long
Python 3.x is a little easier since everything is a PyLong.
>
> How to properly check for integer values?
>
> OTOH, I tried PyNumber_Check() and:
>
> (1) The doc says: Returns 1 if the object o provides numeric protocols, and
> false otherwise. This function always succeeds.
>
> What do they mean: "always succeeds" ?
That it will always return true or false; it won't raise an error.
>
> (2) It seems PyNumber_check(py_val) returns true when passed an instance!
>
> Please advise.
>
> --
> Elias
casevh
More information about the Python-list
mailing list