pythonc++nonetypepyobject

Check if PyObject is None


I would just like to check if a PyObject that I have is None. I naively expected that any None Pyobject * returned from a function would be a NULL pointer, but that doesn't seem to be the case.

So: how do I check if a PyObject * of mine points to a None object?

I know that there are macros like PyInt_Check(PyObject *) around, but I couldn't find anything like PyNone_Check. I thought I could just check the equality between my PyObject and Py_None, but turns out I don't even know how to make equality comparisons with this library.


Solution

  • You can just compare directly with Py_None using ==:

    if (obj == Py_None)
    

    From the docs:

    Note that the PyTypeObject for None is not directly exposed in the Python/C API. Since None is a singleton, testing for object identity (using == in C) is sufficient. There is no PyNone_Check() function for the same reason.