Why Cython forces declaration of locals at the beg

2020-04-21 04:49发布

问题:

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 ?

回答1:

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.

  • In C/C++, the scope of a local variable is from the point it was declared until the end of the most inside block where it was declared.
  • In Python a variable is considered as local in a function if it is assigned somewhere in the function. Then it can be used anywhere inside the function.

To patch up those two rules, Cython developpers decided that local variable declaration are only allowed at the beginning of the function.