cdef statement not allowed here for structure

2019-06-20 05:54发布

问题:

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

cdef struct A:
    int x
    int y
    int z

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

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.

回答1:

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:

  • It's more clear: Users coming into Cython with a C background will not be surprised when their variables don't have the scope that they might expect.
  • It means that the C code generated by Cython more closely tracks the original Cython code, which, I'm sure, makes for easier debugging and implementation for the Cython developers.


标签: cython