Eric
Eric

Reputation: 996

Python package Cython module

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!

Upvotes: 3

Views: 1917

Answers (1)

danny
danny

Reputation: 5270

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.

Upvotes: 3

Related Questions