为什么Cython在函数开始时强制声明本地人 [英] Why Cython forces declaration of locals at the beginning of a function
问题描述
在 Cython-复制构造函数中,有人将此作为评论进行询问.
This was asked as a comment in Cython - copy constructors.
以下代码无法在Cython中编译:
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
这是完全正确的:
def foo(int i):
cdef int j
if i == 0:
return i
else:
j = i+1
return j
问题是:为什么Cython强迫在开始时声明j
功能,而不是在else
块中?
The question is: why does Cython forces to declare j
at the beginning of the
function and not in the else
block ?
推荐答案
原因是Python与C/C ++的作用域规则.
The reason is scoping rule in Python vs C/C++.
Cython试图使Python和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.
- 在C/C ++中,局部变量的范围是从声明它的位置到声明该变量的最里面的块的末尾.
- 在Python中,如果变量在函数中的某处分配,则该变量将被视为函数中的局部变量.然后可以在函数内部的任何位置使用它.
为修补这两个规则,Cython开发人员决定只在函数的开头才允许局部变量声明.
To patch up those two rules, Cython developpers decided that local variable declaration are only allowed at the beginning of the function.
这篇关于为什么Cython在函数开始时强制声明本地人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!