【问题标题】:Cython compilation error - local variable referenced before assignmentCython 编译错误 - 分配前引用的局部变量
【发布时间】:2014-02-21 15:58:09
【问题描述】:

我是 Cython 的新手,并试图通过在关键 AI 模块中使用 Cython 代码来加速我的 kivy 手机游戏。我的代码如下:

import numpy as np
cimport numpy as np

 #not relevant parts

cdef np.ndarray posarr
cdef np.int poslast = 0
cdef np.int posidx = 0

def posarr_init(np.ndarray pawnpos, np.int act):
    poslast = 0
    # not relevant, but referencing poslast

 #not relevant, but including function where poslast is referenced (not assigned)

def consider_pawn(np.int x, np.int y):
    cdef np.int pact, posx, posy, resx, resy
    cdef np.int p
    cdef np.int found = 0
    #not relevant

    #in the code there is this line, posx and posy are local variables
                    posarr[poslast, posx, posy] = posarr[posidx, posx, posy]

Cython 在编译期间给了我这个错误:

Error compiling Cython file:

------------------------------------------------------------
...
                pact = 1
        if pact == 1:
            #pawn is active, create child position
            for posx in range(11):
                for posy in range(11):
                    posarr[poslast, posx, posy] = posarr[posidx, posx, posy]
                                 ^
------------------------------------------------------------

position.pyx:98:34: local variable 'poslast' referenced before assignment

我可以看到 Cython 编译错误的报告顺序与它们在代码中出现的顺序相同。我的问题是:

为什么 Cython 将 poslast 视为局部变量?

在之前的函数中为什么不把它当作局部变量呢?

生成的 C 文件是空的,它只有一条消息,它不应该在里面使用。即使出现编译错误,有没有办法强制 Cython 将 C 代码留在文件中?也许查看这个文件可以帮助我理解错误消息(即为什么这个变量被认为是本地的)......

【问题讨论】:

    标签: python numpy compiler-errors cython


    【解决方案1】:

    简答

    使用global 语句在写入它的每个函数中将poslast 显式声明为全局。

    长答案

    Cython 遵循 Python 绑定规则:如果在函数中为 anywhere 分配了一个名称,则假定它是一个局部变量,除非您明确将其声明为全局变量。

    我猜您在示例循环之后执行并分配给poslast,这使其成为隐式声明的局部变量(object 类型)。然后循环似乎使用了这个尚未初始化的本地。

    您的posarr_init 函数同样不正确。它分配隐式声明的本地 poslast 而无需触及全局。

    【讨论】:

    • +1。 Cython 还支持 nonlocal 关键字(Python 3)
    猜你喜欢
    • 2018-07-16
    • 2014-08-20
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    相关资源
    最近更新 更多