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):or, identically:
pass
def empty2(*args):Despite the simplicity of the task, there are right and wrong ways to
return None
perform it. The canonical solution is:
static PyObject*and the simplest, but still correct way, is:
empty3(PyObject* self, PyObject* args)
{
Py_INCREF(Py_None);
return Py_None;
}
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*Either explicitly Py_INCREF the
empty5(PyObject* self, PyObject* args)
{
return Py_None; /* ***WRONG*** */
}
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/extl;
documentation on the Python C API is at http://www.python.org/doc/current/api/apil.