Why Cython forces declaration of locals at the beginning of a function

一世执手 提交于 2019-12-31 03:54:08

问题


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.



来源:https://stackoverflow.com/questions/21572718/why-cython-forces-declaration-of-locals-at-the-beginning-of-a-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!