How to DECREF an Python object to return?

Ahn, Jae-wook mail at codex.pe.kr
Fri Jan 5 18:41:16 EST 2001


Thank you for your replies. But I still have memory leaks. I have to call
this routine about million times in my python script, the problem is very
serious. System hangs after exhausting every swap memory... :)

I tried to both methods you introduced.

1)

PyObject *res, *tuple;

tuple = PyTuple_New(num);

for(i = 0; i < num; i++)
    PyTuple_SetItem(tuple, i, noun);

res = Py_BuildValue(O, tuple);
Py_DECREF(tuple);
return res;

Memory leaks here... Maybe res must be Py_DECREF also, I think.

2)

PyObject *res, *tuple;

tuple = PyTuple_New(num);

for(i = 0; i < num; i++)
    PyTuple_SetItem(tuple, i, noun);

 return Py_BuildValue("N", poTermTuple);

Memory still leaks, maybe because poTermTuple already exists.

3) So I tried,

PyObject *res, *tuple;

tuple = PyTuple_New(num);

for(i = 0; i < num; i++)
    PyTuple_SetItem(tuple, i, noun);

res = Py_BuildValue(N, tuple);
Py_DECREF(tuple);
return res;

In this case, refcount is 0 and I get nothing.

I thought about another way, and it has no memory leak problem. I wrote a C
function, freeobj() like this.

static PyObject *_mymodule_freeobj(PyObject *self, PyObject *args)
{
 PyObject *tuple;

 if(!PyArg_ParseTuple(args, "O", &tuple))
  return NULL;

 Py_DECREF(tuple);

 return Py_BuildValue("");
}

and called this function in Python after calling the previous one.

    # python script
    res = _mymodule.get_stems(string) # without any Py_DECREF
    _mymodule.freeobj(res)    # Py_DECREF here
    return res

This works, but it's not neat. :) How can I merge this two C modules into
one?

Thank you in advance...

Ahn.








More information about the Python-list mailing list