How to use const in Cython

constants, cython, python

Solution

`const` works for function arguments, but not for this construct because of how Cython compiles it to C.

cdef double a = 2.5

becomes

double __pyx_v_a;
/* lots of other declarations */

__pyx_v_a = 2.5;

and this wouldn't work with a `const` variable. In effect, you cannot use `const` in Cython in all the places were you can use it in C.

Problem

I have read in this link: https://github.com/cython/cython/wiki/FAQ#id35 that my Cython 0.20.1 should be able to support const. However my following code does not compile: ``` cdef const double a = 2.5 print(a) ``` During compilation it says ``` test.pyx:5:5: Assignment to const 'a' Traceback (most recent call last): File "setup1.py", line 11, in <module> ext_modules = cythonize(extensions) File "X:\WinPython3\python-3.3.5.amd64\lib\site-packages\Cython\Build\Dependencies.py", line 785, in cythonize cythonize_one(*args[1:]) File "X:\WinPython3\python-3.3.5.amd64\lib\site-packages\Cython\Build\Dependencies.py", line 902, in cythonize_one raise CompileError(None, pyx_file) Cython.Compiler.Errors.CompileError: test.pyx ```

Original source