Python code and C code in the same module?

S

Steven Bethard

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.

Thanks,

Steve
 
F

Fredrik Lundh

Steven said:
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>
 
N

Nick Coghlan

Fredrik said:
if you insist on doing it the other way around,

This paragraph should actually continue ". . .you clearly have too much free
time" };>

Cheers,
Nick.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top