Python code and C code in the same module?

Fredrik Lundh fredrik at pythonware.com
Tue Nov 30 03:03:03 EST 2004


Steven Bethard wrote:

> I'd like to merge a module written in C with a module written in Python so that the user can 
> access objects from either module by importing the single, merged module.
>
> Specifically, I'm looking at the collections module, which is written in C, and my Bunch object, 
> which is written in Python.  I'd like the Bunch object to appear in the collections module so that 
> you can do:
>
>     from collections import Bunch
>
> without, of course, removing the ability to do:
>
>     from collections import deque
>
> There's no need for the code to reside in the same file or anything of course -- I just want the 
> different objects to appear in the same module.

the usual way to do this is to expose the C objects via the Python
module:

    # foo.py
    from _foo import flubb, glubb, dubb

    # main.py
    import foo

    foo.flubb(flabb)

if you insist on doing it the other way around, you can emulate from-import
on the C level.  see e.g. the "call" function in Modules/_sre.c for an example
(but instead of calling the "func", add it to the local module; see the "init_sre"
function in the same module for code that adds stuff to the module dict).

</F> 






More information about the Python-list mailing list