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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With