Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using and importing/cimporting nested packages in Cython

Is it possible to use nested packages (aka subdirectories) in a Cython extension, and if so, how should I do that?

It seems Cython does not allow a relative import/cimport beyond the the top level package. So, let's say I have the following Cython project structure:

/lib_interface.pyx
/lib_interface.pxd // the top level source files
/submodule/__init__.pxd
/submodule/submodule_code.pyx
/submodule/submodule_code.pxd

Let's imagine our resulted Cython lib is called SomeLib, so in Python I expect doing this: from SomeLib.submodule import SomeClass

but that results into the error saying that "SomeLib.submodule" is not a package.

I tried cimporting and importing submodule into lib_interface.pxd, but that never helped.

like image 424
D. Skarn Avatar asked Nov 07 '22 07:11

D. Skarn


1 Answers

If you want to import stuff into another Cython module, you will need the __init__.pxd at each directory. If you also want to import it into Python, add the usual __init__.py at each level. So your directory structure looks like:

/lib_interface.pyx
/lib_interface.pxd
/__init__.py
/submodule/__init__.pxd
/submodule/submodule_code.pyx
/submodule/submodule_code.pxd
/submodule/__init__.py

And this goes in the __init__.py under submodule directory:

from somelib.submodule.submodule_code import MyClass

__all__ = [MyClass]

Now you should be able to import this as from somelib.submodule import MyClass.

like image 190
Prodipta Ghosh Avatar answered Nov 14 '22 22:11

Prodipta Ghosh