此处不允许使用cdef语句进行结构 [英] cdef statement not allowed here for structure

查看:239
本文介绍了此处不允许使用cdef语句进行结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有结构定义(Astruct.pxd)的简单Astruct.pyx:

I have a simple Astruct.pyx with a struct definition (Astruct.pxd):

cdef struct A:
    int x
    int y
    int z

还有Cython函数,使用它的(struct_test.pyx):

And a Cython function, that uses it (struct_test.pyx):

from random import randint
from Astruct cimport A

def do():
    N = 1000000
    M = 65535
    As = []
    total = 0
    for i in xrange(N):
        cdef A a
        a.x = randint(0, M)
        a.y = randint(0, M)
        a.z = randint(0, M)
        As.append(a)
    for i in xrange(N):
        total += As[i].x + As[i].y + As[i].z
    print total

但是,当我尝试构建struct_test.pyx时,出现此错误:此处不允许使用cdef语句,指向 cdef A a。如果变量在循环之外,它不会抱怨A变量的另一个定义,但是我不明白for循环有什么特别之处。

However, when I try to build struct_test.pyx, I get this error: "cdef statement not allowed here", pointing at "cdef A a". It does not complain about another definition of A variable if it is outside the loop, but I do not understand what is so special about for loop.

推荐答案

Python和C具有不同的作用域规则。 Cython使用与Python相同的范围规则,因此在 / / / /中将变量声明(首次分配) while 或其他块在整个函数的范围内。对于使用 cdef 声明的变量也是如此,但是如您所见,这些变量必须在函数级别而不是子块中声明。

Python and C have different scoping rules. Cython uses the same scoping rules as Python so variables "declared" (first assigned) inside of a for/if/while or other block are in scope for the whole function. This is also true for variables declared using cdef, but as you've seen these variable must be declared at the function level and not in a sub-block.

我可以想到至少有两个充分的理由有此要求:

I can think of at least two good reasons to have this requirement:


  • :当用户的变量没有预期的作用域时,具有C背景的Cython用户将不会感到惊讶。

  • 这意味着Cython生成的C代码会更紧密地跟踪可以肯定,原始的Cython代码可以简化Cython开发人员的调试和实现。

这篇关于此处不允许使用cdef语句进行结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆