Why does Cython force local residents to be declared at the beginning of a function

This is given as a comment in Cython - copy constructors .

The following code does not compile in Cython:

def bar(int i): if i == 0: return i else: cdef int j j = i+1 return j 

whereas this is absolutely correct:

 def foo(int i): cdef int j if i == 0: return i else: j = i+1 return j 

Question: why are Sitons forced to declare j at the beginning and not in the else block?

+1
scope cython local
source share
1 answer

The reason is the scope rule in Python vs C / C ++.

Cython is trying to improve the world of Python and C / C ++. But there are some incompatibilities between these two worlds. The rule of definition is one.

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

To fix these two rules, Cython developers decided that declaring a local variable is allowed only at the beginning of the function.

+2
source share

All Articles