This was asked as a comment in Cython - copy constructors.
The following code doesn't compile in Cython:
def bar(int i):
if i == 0:
return i
else:
cdef int j
j = i+1
return j
whereas this one is perfectly correct:
def foo(int i):
cdef int j
if i == 0:
return i
else:
j = i+1
return j
The question is: why does Cython forces to declare j
at the beginning of the
function and not in the else
block ?
The reason is scoping rule in Python vs C/C++.
Cython is trying to get the better of both Python and C/C++ world. But there are some incompatibilities between those two worlds. Scoping rule is one.
To patch up those two rules, Cython developpers decided that local variable declaration are only allowed at the beginning of the function.