26

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.

2 Answers 2

32

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.

Sign up to request clarification or add additional context in comments.

Comments

0

For anyone that may come across this, as of 3.10 there is now the Py_IsNone() function which the docs state:

Test if an object is the None singleton, the same as x is None in Python.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.