PyLong_Check() wrongly detecting PyBool type?

58 views Asked by At

I'm using Python C API in my C++ program. I have a function like this one (simplified) that returns the a string with the type of a given PyObject passed as argument:

#include <Python.h>

static std::string getPyObjectType(PyObject* obj)
{
  if (PyLong_Check(obj))
  {
    return "long";
  }
  else if (PyFloat_Check(obj))
  {
    return "float";
  }
  else if (PyBool_Check(obj))
  {
    return "bool";
  }
  else
  {
    return "other";
  }
}

The problem is that is not properly detecting boolean objects. When obj is a boolean, it returns "long" instead of "bool". It is like PyLong_Check() were wrongly return true in this case...

If I use a breakpoint in the function to check the type of the obj in this case seems to be right (it shows PyBool_Type):

enter image description here

What's the fail in my code?

Thanks in advance!

1

There are 1 answers

2
Vaija Khushal Vardhan Reddy On

cheeck for bool at the top of the ladder if statements

#include <Python.h>

static std::string getPyObjectType(PyObject* obj)
{
  if (PyBool_Check(obj))
  {
    return "bool";
  }
  else if (PyLong_Check(obj))
  {
    return "long";
  }
  else if (PyFloat_Check(obj))
  {
    return "float";
  }
  else
  {
    return "other";
  }
}