daiyue
daiyue

Reputation: 7448

import Cython modules in Python files from different packages

I created and built a Cython file in a separated package from other python packages, the project has the following directory structure,

pack1
    pack1.1
        cython_file.pyx
        setup.py
pack2
    main_python.py

Along with the pyx file, there is also a package called build and a pyd file been generated after building the Cython file.

the setup.py looks like,

from distutils.core import setup
from Cython.Build import cythonize

setup(
    ext_modules=cythonize("cython_file.pyx")
)

I import cython_file in main.py, like

from pack1.pack1.1.cython_file import cython_func

but got an error:

ImportError: No module named 'pack1.pack1.1.cython_file'

how to resolve the issue?

Upvotes: 5

Views: 12987

Answers (1)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160377

Initially, you should not name a folder pack1.1. Using the . here will make python search for a package with the name 1 (dots seperate packages in the import statement); since Python grammar does not allow names to begin with digits you'll get a syntax error. Opt for a name like pack1_1.

Now, trying to import from a sibling directory is relatively tricky and not suggested; your best option would be to move the main_python.py in the top level directory, if it is the main script, it should live there. Your structure should look like:

pack1
    pack1_1
        cython_file.pyx
        setup.py
main_python.py

Now executing main_python.py:

from pack1.pack1_1.cython_file import cython_func
cython_func()

With a cython_file.pyx of:

cpdef cython_func():
    print("Cython Function Called")

results in the desired result.


If you really need to have that directory structure, you'll need to deploy a little trickery by adding the top directory to sys.path:

import sys, os
sys.path.insert(0, os.path.abspath(".."))
from pack1.pack1_1.cython_file import cython_func

cython_func()

but this is ugly and you won't find people suggesting it.

Upvotes: 5

Related Questions