Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cdef list my_list in Cython

Tags:

python

cython

I am confused about the following code that I see in a lot of places:

cdef list my_list

I am confused because list is not a C data type, but a Python data type. Why would people use cdef instead of def then?

I like this feature a lot, because sometimes I need to use list in my code and it will take a tremendous amount of effort to restructure my code to C without a python list. I am just confused how and what Cython is doing, when a list was defined by cdef and have all the methods exposed to us.

I tried to search the document, but without luck. Any help would be appreciated!

like image 645
Yuxiang Wang Avatar asked Dec 16 '25 11:12

Yuxiang Wang


1 Answers

cdefing a Python data type just allows Cython to take a few (small) shortcuts and to type-check.

This will not result in significantly faster code, as the Python overhead still exists. For convenient data types you'll wanting to be using numpy.array or cpython.array.array typed to a memoryview.

like image 128
Veedrac Avatar answered Dec 19 '25 00:12

Veedrac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!