EsoErik

Tuesday, October 21, 2014

 

Detecting None object in Python C API

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 */
        ...
    }
}

Comments:
Hi man. I track https://stackoverflow.com/questions/17714635/how-can-i-compile-boost-1-54-0-1-54-for-the-ios-simulator-6-1-on-os-x-10-8-4/18495875#18495875 and come up here to ask help form you about build boost::context on ARM.
Can you help me, my email is eversaylove at gmail dot com
 

Post a Comment

Subscribe to Post Comments [Atom]





<< Home

Archives

July 2009   August 2009   September 2009   October 2009   November 2009   December 2009   January 2010   September 2010   December 2010   January 2011   February 2011   April 2011   June 2011   August 2011   February 2012   June 2012   July 2012   August 2012   October 2012   November 2012   January 2014   April 2014   June 2014   August 2014   September 2014   October 2014   January 2015   March 2015   April 2015   June 2015   November 2015   December 2015   January 2016   June 2016   August 2016   January 2017   March 2017  

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]