spacegoing
spacegoing

Reputation: 5306

Cython: C-level int vs. PyLongObjects

I'm reading the book "Cython" written by Kurt W. Smith. I'm confused by this book.

On page 42 the author said:

In cases where Python built-in types like int or float have the same name as a C type, the C type takes precedence. This is almost always what we want.

However on page 44, the author said:

Python also has a PyLongObject at the C level to represent arbitrarily sized integers. In Python 2, these are exposed as the long type, and if an operation with PyIntObject overflows, a PyLongObject results.

In Python 3, at the C level, all integers are PyLongObjects.

My question is if I declared a variable in Python 3, say

cdef int a;

Is a a C-level int because C type takes precedence, or a PyLongObject?

If it's a C-level int, how to interpret the second part?

Upvotes: 1

Views: 667

Answers (2)

Alex Riley
Alex Riley

Reputation: 176978

cdef int a declares a C-level integer in both Python 2 and 3; the C type takes precedence.

All the author appears to be saying is that int in pure Python 3 always means the PyLongObject type. There is no distinction between Python int and long numerical types now.

Python 2 had the long type to mean PyLongObject types, but this has been removed in Python 3 which just has int to refer to PyLongObject types. Therefore there is no potential conflict with builtin types when you write cdef long a when using Cython with Python 3.

Upvotes: 1

Phillip
Phillip

Reputation: 13678

The simplest solution to questions of this kind is to just give it a try and see what happens:

$ cat > foo.pyx
cdef int mytestint
mytestint = 1
$ cython foo.pyx 
$ grep mytestint foo.c | head -n 1
static int __pyx_v_3foo_mytestint;

Upvotes: 0

Related Questions