LondonRob
LondonRob

Reputation: 78723

Call cdef function in cython cell magic

I have a cython module saved as foo.pyx as follows:

cdef double sum(double[:] memview):
    cdef total = 0
    for i in range(len(memview):
        total += memview[i]
    return total

which I then compile with !cython -a foo.pyx.

I want to test this function in a cython cell magic as follows:

  In [1]: %%cython
     ...: import foo
     ...: cimport numpy as np
     ...: import numpy as np
     ...: def get_sum():
     ...:     cdef double[:] to_sum = np.array([1.0,2.0,3.0])
     ...:     cdef double sum = foo.sum(to_sum)
     ...:     return sum

But when I try get_sum() I get:

AttributeError: 'module' object has no attribute 'sum'

What am I doing wrong here?

Upvotes: 1

Views: 1083

Answers (1)

IanH
IanH

Reputation: 10690

To make this work, you need to cimport the cython module. That will require a corresponding pxd that contains the function signature you wish to export from your module. See the relevant part of the documentation for a full working example.

This assumes that your files are all in the same working directory. Otherwise, you will need to include the relevant folders containing the relevant folders containing the pyx and pxd files in the include_dirs argument passed to the Extension class constructor in your setup.py files for the different modules.

Upvotes: 2

Related Questions