Zephyr
Zephyr

Reputation: 12506

Cython/Python comparison invalid syntax error

I would like to compare Python with Cython in term of time execution, so I wrote two files:

fac.py

def factorial(n):
    if n >= 1:
        return n*factorial(n - 1)
    return 1

fastfac.pyx

cpdef long fastfactorial(long n):
    if n>= 1:
        return n*fastfactorial(n - 1)
    return 1

Then I wrote a setup file:

setup.py

from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules = cythonize('fastfac.pyx'))

From the Powershell I executed the two commands:

pip install Cython
python setup.py build_ext --inplace

From the second command I get the following message:

Compiling fastfac.pyx because it changed.
[1/1] Cythonizing fastfac.pyx
C:\Users\.....\venv\lib\site-packages\Cython\Compiler\Main.py:369: FutureWarning: Cython directive 'language_level' not set, using 2 for now (Py2). This will change in a later release! File: C:\Users\.....\fastfac.pyx
  tree = Parsing.p_module(s, pxd, full_module_name)
running build_ext
building 'fastfac' extension
error: Unable to find vcvarsall.bat

However I tried to make a comparison, so I wrote the file:

comparison.py

from fastfac import fastfactorial
from fac import factorial
from timeit import timeit

print(timeit('fastfactorial(20)', globals = globals(), number = 10000))
print(timeit('factorial(20)', globals = globals(), number = 10000))

When I run it, I get this error message:

Traceback (most recent call last):
  File "C:/Users/...../comparison.py", line 1, in <module>
    from fastfac import fastfactorial
ModuleNotFoundError: No module named 'fastfac'

It seems that in the file python.pyx the definition cpdef long fastfactorial(long n) is not recognized as a regular function definition but as a syntax error; in fact, if I try to run that file I get the error message:

  File "C:/Users/...../fastfac.pyx", line 1
    cpdef long fastfactorial(long n):
             ^
SyntaxError: invalid syntax

How can I solve? How can I correctly define a cpdef inside a .pyx file? what am I missing?

Upvotes: 1

Views: 1675

Answers (1)

FiddleStix
FiddleStix

Reputation: 3731

The problem is not your definition of fastfactorial, it is the fact that your setup.py exited with an error and, presumably, without compiling fastfac into a c library. In general, you should always fix such errors.

Your error appears to be happening because you don't have a Microsoft Visual C++ compiler installed. You can follow the instructions in this answer to choose a version of Visual C++ to install.

You also have a warning about the language_level not being set. You shouldn't ignore warnings either so it is worth explicitly stating the level in your setup.py.

setup(ext_modules=cythonize('fastfac.pyx'), language_level=3)

Upvotes: 1

Related Questions