-1

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.

pat
  • 12,587
  • 1
  • 23
  • 52
JohnJ
  • 6,736
  • 13
  • 49
  • 82

1 Answers1

2

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.

Bakuriu
  • 98,325
  • 22
  • 197
  • 231
  • Thank you very much for your explanation. I quite new to C (as in, I have forgot most of it!) - but what does: `return _fib(n-1) + _fib(n-2);` exactly do here? – JohnJ Mar 14 '14 at 16:50
  • @JohnJ it's recursively computing the fibonacci sequence by calling itself over and over - https://www.khanacademy.org/science/computer-science-subject/computer-science/v/recursive-fibonacci-example – TessellatingHeckler Mar 14 '14 at 17:04
  • @TessellatingHeckler: thanks so much. That clears it up for me. Accepted this answer! – JohnJ Mar 14 '14 at 17:10
  • @JohnJ Note that the given implementation of `_fib` is *extremely* slow (aka take exponential time with respect to `n`). There are many better ways to compute them, just search on the web if you don't know them already. – Bakuriu Mar 14 '14 at 21:23
  • Thanks @Bakuriu for your tip. Fortunately I do not have a need to compute them - I was simply learning from the example. Thanks again for the heads up. – JohnJ Mar 17 '14 at 13:31