3

I have the following package structure:

+ repo/
+ setup.py
+ package/
    + module1/
        + submodule1.py
        + submodule2.pyx
    + module2/
        + submodule3.py

I would like to use submodule2.pyx from submodule1.py by something like:

import submodule2

but I have absolutely no idea how to do this. I tried adding the following lines to my setup.py:

from distutils.core import setup
from setuptools import setup
from Cython.Distutils import build_ext

ext_modules = cythonize(Extension(
        "zindex",
        sources=["ndmg/graph/zindex.pyx"],
        language="c",
))
for e in ext_modules:
    e.pyrex_directives = {"boundscheck": False}

setup(
    name='ndmg',
    ext_modules = ext_modules,
    packages=[
        'package',
        'package.module1',
    ....
)

but was unsuccessful. All of the tutorials I could find had very very simplified examples, so I am not sure how to include Cython modules in my python package when the rest of the package is all just normal python code. Does anybody have any good examples I could follow, or can somebody tell me what I'm doing wrong?

Thanks in advance!

Eric
  • 946
  • 2
  • 12
  • 25
  • Please provide info about OS, compiler, errors (if any)/output while running `python setup.py build_ext --inplace` . Assuming linux, check if you got submodule2.so somewhere in your directory tree. – darked89 Jul 12 '17 at 14:25
  • To be more precise: the compiled module name ends up with i.e.: *.cpython-36m-x86_64-linux-gnu.so – darked89 Jul 12 '17 at 14:33
  • Have you tried `from . import submodule2` in submodule1.py? – J.J. Hakala Jul 12 '17 at 22:59
  • 1
    @Rich Try compiling the PYX first using the `python setup.py build_ext --inplace` which should generate a PYD file. Then you should be able from your first .py script to import it like `from submodule2 import {functionname}`. Then it should import the module and be usable. – Matt Jul 16 '17 at 03:51

1 Answers1

3

The name given to cythonize is what Cython will use to call the module and what it will be have to be imported as.

The above setup.py will generate a native extension called zindex and will have to be imported as import zindex even within python files in the zindex package.

Here is an example of how to do this:

from distutils.core import setup
from setuptools import setup
from Cython.Distutils import build_ext

ext_modules = cythonize(Extension(
        "ndmg.graph.zindex",
        sources=["ndmg/graph/zindex.pyx"],
        language="c",
))
<..>

Build and install extension.

In a python file under ndmg/graph/py_index.py you can then do.

from zindex import <..>

to import from the cython module.

danny
  • 5,140
  • 1
  • 19
  • 31