0

Looking on simple example of cython code I wonder if CPython interpreter needed some hard-coded hacks to understand cython syntax (e.g. cdef int N) or if it is implemented using some concepts of standard python syntax (e.g. functions, classes, operators etc.)

I mean, I can roughly imagine how the cython backend can be implemented (c-code generation, compilation etc.), but I don't understand how the frontend syntax can be integrated within standard python interpreter without touching the python interpteter itself (i.e. without extending python language beyond standard).

What is cdef ?

In other words, what cdef actually is? Is it a function, operator, or some new keyword? I would understand N = cedef(int) - that would create instance of some class derived from int. But written like that, I don't see how these 3 tokens even interact (1 cdef, 2 int, 3 N) ?

Does the for-loop actually iterate?

if you write code like this:

cdef int    i,N = 1000000
cdef double f   = 0

for i in xrange(N):
     f += (i*i)
print f

The loop for i in xrange(N): is normal python loop. What prevents python interpreter to uselessly iterate 1000000 iterations before cython compile it into to C-code?

Does it work something like this:

N is an instance of some class cdef. xrange call N.__int__() which returns 1, passing the loop only once. The expression f += (i*i) contains only cdef objects, so cython can redefine __add_(), __set__(), __get__() functions in a way that generate C-code for f+=(i*i)

But then I still don't see how the construct for i in xrange() is send to cython, to generate C code from it.

Anyway, it seems quite complicated and fragiel, so perhaps it must be otherwise

Prokop Hapala
  • 2,424
  • 2
  • 30
  • 59
  • There is no need to speculate: just take a look at the generated C-code. – ead Aug 28 '19 at 17:38
  • And python interpreter will not see the cython code (e.g. cdef), as it will become a c-extension when built. – ead Aug 28 '19 at 17:40
  • I don't care how the generated c-code looks like. I care how CPython parse cython-decorated code. – Prokop Hapala Aug 28 '19 at 17:52
  • aha, you are perhaps rigth, the the `.pyx` files are not parsed by CPython, Cython has it's own parser ... right? ... I was asking because I wanted to abuse python interpreter to generate different language. – Prokop Hapala Aug 28 '19 at 17:54

0 Answers0