1.4 The Module's Method Table and Initialization Function

I promised to show how spam_system() is called from Python programs. First, we need to list its name and address in a ``method table'':

static PyMethodDef SpamMethods[] = {
    ...
    {"system",  spam_system, METH_VARARGS},
    ...
    {NULL,      NULL}        /* Sentinel */
};

Note the third entry ("METH_VARARGS"). This is a flag telling the interpreter the calling convention to be used for the C function. It should normally always be "METH_VARARGS" or "METH_VARARGS | METH_KEYWORDS"; a value of 0 means that an obsolete variant of PyArg_ParseTuple() is used.

When using only "METH_VARARGS", the function should expect the Python-level parameters to be passed in as a tuple acceptable for parsing via PyArg_ParseTuple(); more information on this function is provided below.

The METH_KEYWORDS bit may be set in the third field if keyword arguments should be passed to the function. In this case, the C function should accept a third "PyObject *" parameter which will be a dictionary of keywords. Use PyArg_ParseTupleAndKeywords() to parse the arguemts to such a function.

The method table must be passed to the interpreter in the module's initialization function (which should be the only non-static item defined in the module file):

void
initspam()
{
    (void) Py_InitModule("spam", SpamMethods);
}

When the Python program imports module spam for the first time, initspam() is called. It calls Py_InitModule(), which creates a ``module object'' (which is inserted in the dictionary sys.modules under the key "spam"), and inserts built-in function objects into the newly created module based upon the table (an array of PyMethodDef structures) that was passed as its second argument. Py_InitModule() returns a pointer to the module object that it creates (which is unused here). It aborts with a fatal error if the module could not be initialized satisfactorily, so the caller doesn't need to check for errors.

guido@python.org