[Cython] Multiple modules in one compilation unit

Greg Ewing greg.ewing at canterbury.ac.nz
Thu Mar 3 01:01:20 CET 2011


Stefan Behnel wrote:
> you'd call "cython" on a package and it would output a 
> directory with a single __init__.so that contains the modules compiled 
> from all .pyx/.py files in that package. Importing the package would 
> then trigger an import of that __init__.so, which in turn will execute 
> code in its init__init__() function to register the other modules.

I don't think it even has to be a directory with an __init__,
it could just be an ordinary .so file with the name of the
package.

I just tried an experiment in Python:

# onefilepackage.py
import new, sys
blarg = new.module("blarg")
blarg.thing = "This is the thing"
sys.modules["onefilepackage.blarg"] = blarg

and two different ways of importing it:

 >>> from onefilepackage import blarg
 >>> blarg
<module 'blarg' (built-in)>
 >>> blarg.thing
'This is the thing'

 >>> import onefilepackage.blarg
 >>> onefilepackage.blarg.thing
'This is the thing'

So assuming the same thing works with a .so instead of a .py,
all you need to do is emit a .so whose init function stuffs
appropriate entries into sys.modules to make it look like
a package.

-- 
Greg


More information about the cython-devel mailing list