pythonnumpyipythoncythontyped-memory-views

Syntax Error while trying to use Cythons memoryviews


I'm following this guide on memoryviews.

But when I tried the code in the Quickstart section on Jupyter, it gave this error:

Image

  File "<ipython-input-3-33f3a8b46ca3>", line 3
cdef int [:, :, :] narr_view = narr
       ^
SyntaxError: invalid syntax

I don't even know how to search for this error since it's syntax related but this syntax is recommended by Cython.org. I think it may be because I'm using this code in the wrong place (not on Jupyter platform).

Any suggestions would be appreciated.


Solution

  • Each cell is executed by itself, so you need to use %%cython in every cell that should be compiled with cython. You even need to import numpy in every of these cells.

    Use:

    %%cython
    
    import numpy as np
    narr = ...
    
    cdef int[:, :, :] narr_view = narr