Writing extensions

As already said, writing extensions is not a simple task but, in return for your hard work, it can give you a lot of advantages. The easiest approach to creating extensions is to use tools such as Cython or Pyrex. These projects will increase your productivity and also make code easier to develop, read, and maintain.

Anyway, if you are new to this topic, it is good to start your adventure with extensions by writing one using nothing more than bare C language and Python/C API. This will improve your understanding of how extensions work and will also help you to appreciate the advantages of alternative solutions. For the sake of simplicity, we will take a simple algorithmic problem as an example and try to implement it using the two following different approaches:

Our problem will be finding the nth number of the Fibonacci sequence. It is very unlikely that you would like to create the compiled extensions solely for this problem, but it is very simple so it will serve as a very good example of wiring any C function to Python/C API. Our goals are only clarity and simplicity, so we won't try to provide the most efficient solution.

Before we create our first extension let's define a reference implementation that will allow us to compare different solutions. Our reference implementation of the Fibonacci function implemented in pure Python looks as follows:

"""Python module that provides fibonacci sequence function""" 
 
 
def fibonacci(n): 
    """Return nth Fibonacci sequence number computed recursively. 
""" 
    if n < 2: 
        return 1 
    else: 
        return fibonacci(n - 1) + fibonacci(n - 2) 

Note that this is one of the most simple implementations of the fibonnaci() function and a lot of improvements could be applied to it even in Python. We refuse to improve our implementation (using memoization pattern, for instance) because this is not the purpose of our example. In the same manner, we won't optimize our code later when discussing implementations in C or Cython, even though the compiled code gives us many more possibilities to do so.

Let's look into pure C extensions in the next section.