pythonimportsyntax-errorcythoncimport

`cimport` causes error in interactive Python interpreter


Running cimport cython or cimport numpy in the Python interpreter results in the following error:

cimport cython
  File "<interactive input>", line 1
    cimport cython
                 ^
SyntaxError: invalid syntax

Is it environment variables path problem? Or is it not supposed to be run in the interpreter? Please, help. I spent several days trying to get rid of the error. (By the way, I do not get an error when compiling .pyx files that use cimport numpy...) Thank you! Oleg


Solution

  • Cython is a superset of the Python language; it is not a Python module. It has a very similar syntax to Python, but adds additional syntax and functionality that is not compatible with standard Python interpreters, such as CPython (which is probably what you're using). Cython produces C or C++ code that can be compiled into a module that can be imported into CPython.

    You need to compile your Cython program before you run it. See the documentation here: http://docs.cython.org/src/quickstart/build.html

    Once you have compiled your module, you don't need to cimport it - just do a regular import. The cimport command is not recognised by CPython, hence your SyntaxError.