What's the difference using extension type (cdef) and set up pure python code?

Viewed 160

Note that I'm new to the C language. According to Basic Tutorial of Cython, I believe there are two ways of using Cython: Building the extension of pure Python code, and using Ctype variable (cdef).

What I don't understand is the difference between them. Which one of them is the more efficient or proper way to using Cython?

2 Answers

It's mostly historical.

  • Originally Cython only supported cdef declarations.
  • Pure Python mode was added as a way of adding declarations to a file to help speed it up while not requiring Cython.
  • Python added type annotations. Cython can increasingly use these (with the annotation_typing directive, which defaults to true). If you like the syntax of these better than cdef then use them. Or not.

The cdef version is slightly better tested and there's still gaps in what you can do in "pure Python" mode. Especially with respect to interfacing with native C/C++. But mostly they are different ways to achieve the same thing and they should generate largely the same code, so you should use whichever you prefer. You can also use a mixture.

Most Python codes can be directly "cythonized", with no change to your code. Nevertheless, to get the best of Cython, you need to adapt your Python code by providing the cdef and the type of your variables. Not mandatory, but essential to get the decent speed up that you expect from Cython.

Related