Creating a "package" using C extensions?

Alex Martelli aleax at aleax.it
Tue Dec 11 10:10:21 EST 2001


"Chris Barker" <chrishbarker at attbi.com> wrote in message
news:3C14FFDE.97DA740A at attbi.com...
    ...
> IF you figure out how to do this, I'd love to see an example. It owuld
> be prettyhandy for me as well. Maybe even a cookbook entry?

You mean, something like the following pa.py...:

#include <Python.h>

static PyMethodDef nomethods[] = {
  {NULL, NULL}
};

void initmod1()
{
    PyObject* m = Py_InitModule("pa.mod1", nomethods);
    /* add module attributes, if any */
    PyModule_AddStringConstant(m, "foo", "bar1");
}

void initmod2()
{
    PyObject* m = Py_InitModule("pa.mod2", nomethods);
    /* add module attributes, if any */
    PyModule_AddStringConstant(m, "foo", "bar2");
}

void initpa()
{
    PyObject* module;
    PyObject* package = Py_InitModule("pa", nomethods);
    if(!package) return;

    /* add package attributes, if any */
    PyModule_AddStringConstant(package, "foo", "bar");

    module = PyImport_AddModule("pa.mod1");
    if(!module) return;
    if(PyModule_AddObject(package, "mod1", module))
        return;
    Py_INCREF(module);
    initmod1();

    module = PyImport_AddModule("pa.mod2");
    if(!module) return;
    if(PyModule_AddObject(package, "mod2", module))
        return;
    Py_INCREF(module);
    initmod2();
}

Of course, in real life you'd no doubt use something more
substantial as the package's contents, and modules'
contents, rather than these feeble "nomethods" and string
constants, but, is this the gist of what you mean?

I could surely post it as a cookbook recipe, of course.
BTW, the setup.py to build this on any platform, just
for completeness (but it IS rather obvious of course):

from distutils.core import setup, Extension

setup (name = "pa",
       version = "1.0",
       maintainer = "Alex Martelli",
       maintainer_email = "aleax at aleax.it",
       description = "Sample Python multimodule package",

       ext_modules = [Extension('pa',sources=['pa.c'])]
)


Waiting for some feedback (I may have misunderstood, or
made some silly mistake, as I just put this together:-)
before making a recipe of it...


Alex






More information about the Python-list mailing list