1

I am testing relative imports in Cython to use in my own project, but I can't seem to get it working. I also tried this answer, but still couldn't get it to work.

I am using Cython doc's example, but changing the file structure so that it resembles a package:

.
├── main.py
├── setup.py
└── src
    ├── landscaping.pyx
    ├── shrubbing.pxd
    └── shrubbing.pyx

The shrubbing.pxd and .pyx files are the same as the docs, but I changed the landscaping.pyx file to use relative imports.

# landscaping.pyx
from . cimport shrubbing
from . import shrubbing

def main():
    cdef shrubbing.Shrubbery sh
    sh = shrubbing.standard_shrubbery()
    print("Shrubbery size is", sh.width, 'x', sh.length)

However, when I run python setup.py:

# setup.py
import sys
sys.argv = ["setup.py", "build_ext", "--inplace"]

from setuptools import setup, Extension
from Cython.Build import cythonize

ext_modules = [
    Extension('landscaping', ['src/landscaping.pyx']),
    Extension('shrubbing', ['src/shrubbing.pyx']),
]

setup(
    ext_modules=cythonize(ext_modules),
    include_dirs=['.'],
)

It gives this error:

error compiling Cython file:
------------------------------------------------------------
...
from . cimport shrubbing
^
------------------------------------------------------------

src/landscaping.pyx:1:0: relative cimport beyond main package is not allowed

I've been stuck on this for weeks, trying to change setuptools.setup arguments such as the include_dirs and whatnot, but without success.

Edit 1:
I know the problem is that when compiling, the main package becomes the folder the file being compiled lies in, but my include_dirs is the base directory above src/, so is this a bug or am I missing something?

  • Whatever the motivation to split into two extensions, sources for `landscaping` don't include `shrubbing.pyx` - it is not supposed to work – Marat Jun 17 '22 at 03:43
  • That is not true. If I remove the relative imports and put the three files in the base directory, it works. Also the docs also generates two separate files. – William Hou Jun 17 '22 at 08:29

1 Answers1

0

It turns out that this is a bug, and should be fixed with this pull request! Note that it is not working in the current version 29.3, but should be fixed in the next version.