Trying to cimport pxd definitions from other packages.
Simple example, a.pxd file:
cdef inline void a():
print "a"
b.pyx file:
cimport a
def b():
a.a()
Until here, everything is ok, and $ cython b.pyx
works.
If i move a.pxd to a folder, e.g libs/
, then I change b.pyx to:
from libs cimport a
def b():
a.a()
and then I have the error:
$ cython b.pyx
Error compiling Cython file:
------------------------------------------------------------
...
from libs cimport a
^
------------------------------------------------------------
b.pyx:1:0: 'a.pxd' not found
Error compiling Cython file:
------------------------------------------------------------
...
from libs cimport a
^
------------------------------------------------------------
b.pyx:1:0: 'libs/a.pxd' not found
But libs/a.pxd is there. What would be the right way to import pxd definitions from other packages?
In addition to the . pyx source files, Cython uses . pxd files which work like C header files – they contain Cython declarations (and sometimes code sections) which are only meant for inclusion by Cython modules. A pxd file is imported into a pyx module by using the cimport keyword.
pxd is a definition file which exports a C data type. restaurant. pyx / restaurant.py is an implementation file which imports and uses it.
A directory is not a package unless it contains a __init__.py
file, even if the file is empty. So add an empty __init__.py
file to the libs
directory.
With this directory structure, your a.pxd
and b.pyx
, setup.py
and script.py
(below),
% tree .
.
├── libs
│ ├── a.pxd
│ └── __init__.py
├── b.c
├── b.pyx
├── b.so
├── build
│ ├── temp.linux-x86_64-2.7
│ │ └── b.o
│ └── temp.linux-x86_64-3.4
│ └── b.o
├── script.py
├── setup.py
Running script.py
works:
% python setup.py build_ext --inplace
% python ./script.py
a
setup.py:
# python setup.py build_ext --inplace
from distutils.core import setup
from Cython.Build import cythonize
setup(
name='test',
ext_modules=cythonize("b.pyx"),
)
script.py:
import b
b.b()
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