How to use C code in Python

… and should we do this?

Dorian Lazar
Nabla Squared

--

Background image by Johnson Martin from Pixabay

Before seeing “how” to use C code from Python let’s see first “why” one may want to do this. If you are reading this article right now you probably want to do one or more of these 3 things:

  1. Reusing existing C code from a Python program
  2. Speed up your Python program
  3. Do some low-level stuff that cannot be done directly in Python

A shortcut…

If all you want is just to speed up your Python program, then there is actually an easier way rather than writing certain parts of your program in C. You can just use PyPy instead of Python when executing your app. PyPy is an alternative implementation of the Python programming language which uses just-in-time compilation to speed up the same python code with little or no changes to your code. You can download and install it from here.

After installation, simply replace python with pypy when executing a Python script. So, instead of:

python my_awesome_program.py

do:

pypy my_awesome_program.py

As you will see in the benchmark at the end of this article, this method can make your code considerably faster and in some situations (as is the case with the simple…

--

--

Dorian Lazar
Nabla Squared

Passionate about Data Science, AI, Programming & Math | Owner of ∇² https://www.nablasquared.com/