C api and checking for integers

L

lallous

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.

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" ?

(2) It seems PyNumber_check(py_val) returns true when passed an instance!

Please advise.
 
C

casevh

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.

casevh
 

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

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top