1.3 Back to the Example

Going back to our example function, you should now be able to understand this statement:

    if (!PyArg_ParseTuple(args, "s", &command))
        return NULL;

It returns NULL (the error indicator for functions returning object pointers) if an error is detected in the argument list, relying on the exception set by PyArg_ParseTuple(). Otherwise the string value of the argument has been copied to the local variable command. This is a pointer assignment and you are not supposed to modify the string to which it points (so in Standard C, the variable command should properly be declared as "const char *command").

The next statement is a call to the Unix function system(), passing it the string we just got from PyArg_ParseTuple():

    sts = system(command);

Our spam.system() function must return the value of sts as a Python object. This is done using the function Py_BuildValue(), which is something like the inverse of PyArg_ParseTuple(): it takes a format string and an arbitrary number of C values, and returns a new Python object. More info on Py_BuildValue() is given later.

    return Py_BuildValue("i", sts);

In this case, it will return an integer object. (Yes, even integers are objects on the heap in Python!)

If you have a C function that returns no useful argument (a function returning void), the corresponding Python function must return None. You need this idiom to do so (which is implemented by the Py_RETURN_NONE macro):

    Py_INCREF(Py_None);
    return Py_None;

Py_None is the C name for the special Python object None. It is a genuine Python object rather than a NULL pointer, which means ``error'' in most contexts, as we have seen.

See About this document... for information on suggesting changes.