This is a day-one Python C API question that I have answered about a million times: "how do I detect the None value?"
The answer I have always given is, "read the docs." Today, I got some huge push back on that.
Quoth the Python docs to which I have referred:
The None Object
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.
-
PyObject* Py_None
- The Python None object, denoting lack of value. This object has no methods.
It needs to be treated just like any other object with respect to reference
counts.
-
Py_RETURN_NONE
- Properly handle returning Py_None from within a C function (that is,
increment the reference count of None and return it.)
As you can see, the docs lay it all out. None is a global singleton and you need only test for object identity to distinguish it from not None.
The push back:
"Err, singleton? Global, in what sense? ' Object identity'?? I'm a C programmer! We speak the same words, but yours are without meaning!"
On second thought, the docs do not lay it out.
There are two things you are absolutely sure to want to do with
None values when interacting with the CPython C API. The section of the docs I pasted deals with None values in the context of the CPython C API. What are the two things you actually want to know when you read this section of the docs?
1: HOW TO RETURN NONE FROM C
Call the Py_RETURN_NONE macro.
2: HOW TO DETECT A NONE VALUE IN C
There is no PyNone_Check() function, but testing for object identity is OK. So, test for identity:
PyObject* blah(PyObject* foo){
if(foo == Py_None){
/* argument is None; let's return None */
Py_RETURN_NONE;
}else{
/* do something and return python object */
...
}
}
Post a Comment