Recipe17.8.Returning None from a Python-Callable C Function


Recipe 17.8. Returning None from a Python-Callable C Function

Credit: Alex Martelli

Problem

Your C-coded, Python-callable function in an extension module needs to return nothing in particular (i.e., a Python None), but it must, of course, do so without messing up reference counts.

Solution

Suppose we need an empty C-coded function, equivalent to Python:

def empty1(*args):     pass

or, identically:

def empty2(*args):     return None

Despite the simplicity of the task, there are right and wrong ways to perform it. The canonical solution is:

static PyObject* empty3(PyObject* self, PyObject* args) {     Py_INCREF(Py_None);     return Py_None; }

and the simplest, but still correct way, is:

static PyObject* empty4(PyObject* self, PyObject* args) {     return Py_BuildValue(""); }

Discussion

A function written in C for Python often needs to return nothing in particular. In Python terms, it must return None. Don't just code return Py_None; from C: that messes up reference counts! Nonethe Python object we must explicitly return from a Python-callable, C-coded functionis a normal Python object, subject to all normal reference count rules. One of these rules is that each function must Py_INCREF the Python object it returns.

A bare return Py_None; is a nasty lurking buga frequent beginner's error that messes up reference counts:

static PyObject* empty5(PyObject* self, PyObject* args) {     return Py_None;          /* ***WRONG*** */ }

Either explicitly Py_INCREF the None object you're returning, or (a simpler approach, but one that costs a few machine cycles) delegate the work to the handy function Py_BuildValue, which can be used to handle just about all cases of returning values from C to Python, offering potential uniformity advantages. To have Py_BuildValue build a properly incref'd None on your behalf, call it with just one argument, an empty format string.

In Python 2.4, the C API has gained a new macro just for this purpose. If you're coding a C extension that supports only Python 2.4, you can write Py_RETURN_NONE; instead of the return statement, and the macro takes care of everything for you.

See Also

The Extending and Embedding manual is available as part of the standard Python documentation set at http://www.python.org/doc/current/ext/ext.html; documentation on the Python C API is at http://www.python.org/doc/current/api/api.html.



Python Cookbook
Python Cookbook
ISBN: 0596007973
EAN: 2147483647
Year: 2004
Pages: 420

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net