Linux/Unix > Python Essential Reference, Second Edition > B. Extending and Embedding Python > Enabling Optional Modules | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238111161105094192216208231183024

### Enabling Optional Modules

A number of modules in the standard library are disabled due to system differences and dependencies on third-party packages. To enable these modules, you must edit a configuration file and rebuild the interpreter (note that this is primarily an issue for UNIX systems).

For versions of Python prior to 2.1, the file `Modules/Setup` in the Python source distribution contains configuration data for modules built into the Python interpreter. It contains entries of this form:

    signal signalmodule.c          # signal(2)
    ...
    #readline readline.c -lreadline -ltermcap

Each line indicates the name of a module, followed by source files, compiler options, and link libraries needed to compile that module. A line starting with `#` is a comment and denotes modules that have been disabled. Long lines can be broken into multiple lines by placing a backslash (`\`) at the end of lines to be continued. To enable an optional module, the `Setup` file should be edited to reflect the installation locations of required third-party libraries. For example, to enable the `readline` module, the `Setup` file might be modified as follows:

    ...
    readline readline.c -I/usr/local/include -L/usr/local/lib \
             -lreadline -ltermcap

The interpreter must be rebuilt and reinstalled by typing `make` and `make install` in the top-level directory of the source tree for the changes to `Setup` to take effect.

Beginning with Python 2.1, much of the need to edit the `Setup` file has been removed because the Python installation process has been modified to compile only a core of necessary modules into the Python executable. Most modules are now configured as dynamic modules and some effort is made to detect them automatically if it’s possible to build them. For instance, a build of Python 2.1 will automatically enable the `readline` module if it can detect that the necessary libraries are installed during its configuration process. If it’s necessary to manually modify the build process, changes should be made to the `setup.py` file in the main Python 2.1 source directory.

#### Extension Module Example

Extension modules are used to extend the interpreter with functions in C. For example, suppose you wanted to access the following C functions in a Python module named `spam`:

    /* Compute the greatest common divisor of positive
       integers x and y */
    int gcd(int x, int y) {
        int g;
        g = y;
        while (x > 0) {
             g = x;
             x = y % x;
             y = g;
        }
        return g;
    }
    /* Print some data */
    void print_data(char *name, char *email, char *phone) {
        printf("Name    : %s\n", name);
        printf("Email   : %s\n", email);
        printf("Phone   : %s\n", phone);
    }

To access these functions from an extension module, you must write code such as that in Listing B.1:

##### Listing B.1 Accessing Functions from an Extension Module

    /* "spam" module **/
    /* Include the Python C API */
    #include "Python.h"

    /* External declarations */
    extern int gcd(int,int);
    extern void print_data(char *, char *, char *);

    /* Wrapper for the gcd() function */
    PyObject *spam_gcd(PyObject *self, PyObject *args) {
         int x, y, g;
         /* Get Python arguments */
         if (!PyArg_ParseTuple(args,"ii",&x,&y)) {
             return NULL;
         }
         /* Call the C function */
         g = gcd(x,y);
         return Py_BuildValue("i",g);
    }
    /* Wrapper for the print_data() function */
    PyObject *
    spam_print_data(PyObject *self, PyObject *args, PyObject *kwargs)
    {
         char *name = "None";
         char *email = "None";
         char *phone = "None";
         static char *argnames[] = {"name","email","phone",NULL};

         /* Get Python arguments */
         if (!PyArg_ParseTupleAndKeywords(args,kwargs,"|sss",argnames,
               &name,&email,&phone)) {
             return NULL;
         }
         /* Call the C function */
         print_data(name,email,phone);
         return Py_BuildValue("");        /* Return None */
    }
    /* Method table mapping names to wrappers */
    static PyMethodDef spammethods[] = {
         {"gcd", spam_gcd, METH_VARARGS},
         {"print_data", spam_print_data, METH_VARARGS | METH_KEYWORDS },
         {NULL, NULL}
    };
    /* Module initialization function */
    initspam(void) {
         Py_InitModule("spam", spammethods);
    }

Extension modules always need to include `"Python.h"`. For each C function to be accessed, a wrapper function is written. These wrapper functions either accept two arguments (`self` and `args`, both of type `PyObject *`) or three arguments (`self`, `args`, and `kwargs`, all of type `PyObject *`). The `self` parameter is used when the wrapper function is implementing a built-in method to be applied to an instance of some object. In this case, the instance is placed in the `self` parameter. Otherwise, `self` is set to `NULL`. `args` is a tuple containing the function arguments passed by the interpreter. `kwargs` is a dictionary containing keyword arguments.

Arguments are converted from Python to C using the `PyArg_ParseTuple()` or `PyArg_ParseTupleAndKeywords()` function. Similarly, the `Py_BuildValue()` function is used to construct an acceptable return value. These functions are described in later sections.

Functions signal an error by returning `NULL`. If a function has no return value (that is, `void`), the `None` object must be returned. For example:

    PyObject *wrap_foo(PyObject *self, PyObject *args) {
        ...
        /* Return None */
        return Py_BuildValue("");
    }

`None` can also be returned as follows:

    PyObject *wrap_foo(PyObject *self, PyObject *args) {
        ...
        /* Return None */
        Py_INCREF(Py_None);
        return Py_None;
    }

The method table `spammethods` in Listing B.1 is used to associate Python names with the C wrapper functions. These are the names used to call the function from the interpreter. The `METH_VARARGS` flag indicates the calling conventions for a wrapper.

In this case, only positional arguments in the form of a tuple are accepted. It can also be set to `METH_VARARGS | METH_KEYWORDS` to indicate a wrapper function accepting keyword arguments.

The module initialization function `initspam` is used to initialize the contents of the module. In this case, the `Py_InitModule('spam",spammethods)` function creates a module spam and populates it with built-in function objects corresponding to the functions listed in the method table.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.