bzm3r
bzm3r

Reputation: 4615

Cython: how to resolve TypeError: Cannot convert memoryviewslice to numpy.ndarray?

Inside a random_stuff_printer.pyx file, I have a cdef function that looks something like this:

cdef np.ndarray[np.float64_t, ndim=4] randomizer():
    return np.random.random((4, 4, 4, 4))

Then I have a def function that looks like this, inside the same random_stuff_printer.pyx:

def random_printer():
    random_stuff = randomizer()
    print random_stuff

I compile the file, and call random_printer, but I get the following error:

TypeError: Cannot convert random_stuff_printer._memoryviewslice to numpy.ndarray

How can I fix this issue?

Upvotes: 3

Views: 4037

Answers (1)

arokem
arokem

Reputation: 579

I believe that this is an issue of keeping your def, cdefs, and cimport and imports straight. Here's some code that works for me:

import numpy as np
cimport numpy as cnp

cdef cnp.ndarray[cnp.float64_t, ndim=4] randomizer():    
    return np.random.random((4, 4, 4, 4))

def random_printer():
    cdef foo = randomizer()
    print(foo)

See for example this notebook: http://nbviewer.ipython.org/gist/arokem/6fa00ceb17e16c367c8a

Upvotes: 2

Related Questions