A few common misconceptions about Cython

I’m a big fan of Python, I’ve said it before and I’ll proudly say it again. At the same time I’m also a big fan of code that runs fast, really fast, which is why I’m a fan of writing high-performance Python code. A couple of weeks ago I wrote a post about Python Performance Optimization and I got some good emails asking me to delve deeper into some of the topics I discussed.


One of the questions that I got which I thought would be good to start with was:

“So does Cython just take existing Python code and turn it into C code?”

This is one of the most common misconceptions about Cython so I thought I’d talk a bit about what Cython is and some of the confusion around it. Here’s where most of the confusion around Cython stems from in one simple sentence: Cython is both an optimizing static compiler and a programming language based on Pyrex. Confused? Now you can understand why there is so much confusion around Cython.

So here’s a basic look at how Cython works at a (very) high level:

  • start with existing Python code
  • add in some Cython code
  • run this code through the Cython compiler to create super-fast code

Now that we’ve covered the basics, let’s dispel some common misconceptions about Cython.

1. Cython turns existing Python code into C code – not exactly. You need to add Cython code to your code first, just running existing code through the Cython compiler isn’t going to give you the desired results.

2. Cython is the process of writing C code within Python – I’ve seen this confusion a lot as well. It could be easy to think that Cython is simply writing C code inline with your Python code, this isn’t the case, instead as described above you’ll use Cython code along with the Cython compiler to generate C code.

3. Using Cython still won’t make your programs run as fast as they would in C – wrong, and in fact this exact topic was covered (and proven) in this talk at SciPy2013. You can take existing Python code and make it just as fast as C code using Cython, yes it is that awesome!

As always feel free to use the comment section below to ask me any lingering questions you have about Cython or feel free to share some of your own fun Cython facts as well!

Morgan Linton

Morgan Linton