Cdef statement for structure not allowed

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

cdef struct A: int x int y int z 

And the 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 ax = randint(0, M) ay = randint(0, M) az = 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 instruction is not allowed here", pointing to "cdef A a". He does not complain about another definition of variable A if it is outside the loop, but I do not understand what is especially important for the loop.

+6
source share
1 answer

Python and C have different scoping rules. Cython uses the same scope rules as Python, so variables declared (first assigned) inside for / if / while or another block are available to the whole function. This is also true for variables declared with cdef , but as you have seen, this variable should be declared at the function level, and not in the sub-block.

I can come up with at least two good reasons for this requirement:

  • This is more understandable: users coming into Cython with a C background will not be surprised when their variables do not have the capabilities that they can expect.
  • This means that the C code generated by Cython more accurately tracks the source code of Cython, which I am sure simplifies debugging and implementation for Cython developers.
+9
source

Source: https://habr.com/ru/post/973196/


All Articles