One of the great features of Python is the ability to extend its functionality with existing C code. This article presents a minimal example of how to create one of these extension modules.
This example shows calculating the first ‘n’ numbers in the Tribonacci sequence.
The Tribonacci sequence is calculated as a(n) = a(n-1) + a(n-2) + a(n-3).
Creating the module requires the creation of at least 2 files. In our case these files are tribonacci.c and setup.py. tribonacci holds the C code that we’d like available in our python library, and setup.py is used when build our library.
To start, you must create your C source file. Copy the following into a file called tribonacci.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
#include <python2.6/python.h> //a(n) = a(n-1) + a(n-2) + a(n-3) where a(0)=0, a(1)= 0, & a(2)=1 static PyObject * tribonacci( PyObject *self, PyObject *args ) { int a = 0; int b = 0; int c = 1; int d; int n; int x; //Get Arguments if( !PyArg_ParseTuple( args, "i", &n ) ) return 0; PyObject *outList = PyList_New( 0 ); PyObject *num; for( x = 0; x < n; x++ ){ num = PyInt_FromLong(a); PyList_Append(outList, num); Py_DECREF(num); d = a + b + c; a = b; b = c; c = d; } return outList; } PyMethodDef methods[] = { {"tribonacci", tribonacci, METH_VARARGS, "Returns a tribonacci sequence with n elements"}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC inittribonacci( void ) { (void) Py_InitModule( "tribonacci", methods ); } |
and copy this code into a file named setup.py
|
|
from distutils.core import setup, Extension setup( name = "Tribonacci", version = "1.0", description = "Outputs The First 'n' Numbers In The Tribonacci Sequence", author = "Ryan", url = "http://weeklybuild.com/", ext_modules = [Extension("tribonacci", ["tribonacci.c"])] ) |
Now your ready to build and install your new library. Just run the following commands from the command line.
|
|
$ python setup.py build $ python setup.py install |
If there were no errors, you should now have a tribonacci library installed and waiting to be used in your python script. Test your new extension by firing up the Python interpreter and requesting the first 10 numbers in the Tribonacci sequence.
|
|
$ python >>> import tribonacci >>> tribonacci.tribonacci(10) [0, 0, 1, 1, 2, 4, 7, 13, 24, 44] >>> exit() |
And thats it. Pretty cool huh?