Question

I am trying to learn how to extend python using C extensions and so far I have been able to go through the official python docs for the same.

Browsing through, I have found this helpful resource which explains how to extend python using C extensions. So, the example looks like so:

#include <Python.h>

int
_fib(int n)
{
    if (n < 2)
        return n;
    else
        return _fib(n-1) + _fib(n-2);
}

static PyObject*
fib(PyObject* self, PyObject* args)
{
    int n;

    if (!PyArg_ParseTuple(args, "i", &n))
        return NULL;

    return Py_BuildValue("i", _fib(n));
}

static PyMethodDef FibMethods[] = {
    {"fib", fib, METH_VARARGS, "Calculate the Fibonacci numbers."},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC
initfib(void)
{
    (void) Py_InitModule("fib", FibMethods);
}

However, I am having trouble in understanding what this piece of code does:

int
_fib(int n)
{
    if (n < 2)
        return n;
    else
        return _fib(n-1) + _fib(n-2);
}

especially, the _ part of the function name.

I would really appreciate if someone could explain what the above piece of code does.

Was it helpful?

Solution

It's simply plain C code. The _fib function computes the nth fibonacci number.

The _ at the beginning of the name doesn't have any special meaning. It is conventionally (at least in the python community) used to denote "private" functions. They probably used _fib for the C function because they wanted to use fib for the wrapper.

I believe the example was meant to show how you could implement the core functionality as plain C, and add a wrapper to be accessed from python.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top