Nested Python C Extensions/Modules?
How do I compile a C-Python module such that it is local to another? E.g. if I have a module named "bar" and another module named "mymodule", how do I compile "bar" so that it imported via "import mymodule.bar"?
(Sorry if this is poorly phrased, I wasn't sure what the proper term for it was.)
I tried the following in setup.py, but it doesn't seem to work:
from distutils.core import setup, Extension
setup(name='mymodule',
version='1.0',
author='Me',
ext_modules=[Extension('mymodule', ['mymodule-module.c']),
Extension('bar', ['bar-module.c'])])
Edit
Thanks Alex. So this is what I ended up using:
from distutils.core import setup, Extension
PACKAGE_NAME = 'mymodule'
setup(name=PACKAGE_NAME,
version='1.0',
author='Me',
packages=[PACKAGE_NAME]开发者_运维问答,
ext_package=PACKAGE_NAME
ext_modules=[Extension('foo', ['mymodule-foo-module.c']),
Extension('bar', ['mymodule-bar-module.c'])])
with of course a folder named "mymodule" containing __init__.py
.
The instructions are here:
Extension('foo', ['src/foo1.c', 'src/foo2.c'])
describes an extension that lives in the root package, while
Extension('pkg.foo', ['src/foo1.c', 'src/foo2.c'])
describes the same extension in the pkg package. The source files and resulting object code are identical in both cases; the only difference is where in the filesystem (and therefore where in Python’s namespace hierarchy) the resulting extension lives.
Remember, a package is always a directory (or zipfile) containing a module __init__
. To create a module that's a package body, that module will be called __init__
and live under the package's directory (or zipfile). I've never done that in C; if it doesn't work to do it directly, name the module e.g. _init
instead, and in __init__.py
do from _init import *
(one of the very few legitimate uses of from ... import *
;-).
精彩评论