Mailing List Archive

Extension module mystery
I know this will embarrass me, but after fiddling around with it
for an afternoon I'm almost desperate. I and my python interpreter
are having a bad crisis.

I'm trying to write a C extension module for python, basically a
wrapper around a function taking two strings and returning an
integer. This works like a charm, but was too slow when a problem
required that this function was called for quite a number of times.

So I thought I'd cut down on python's function call overhead by
letting the C module perform the operation on an entire list of
strings. So I came up with a function like
static PyObject *list_ldws(char *str,PyObject *strlist)
{ int listlen=PyList_Size(strlist);
PyObject *intlist=PyList_New(listlen);
int i,dist;
char *str2;

/*Py_INCREF(intlist); -- PyList_New does this for me, right?*/
for (i=0;i<listlen;i++)
{ str2 = PyString_AsString(PyList_GetItem(strlist,i));
dist = WLD(str,str2,40);
PyList_SetItem(intlist,i,PyInt_FromLong(dist));
}
return intlist;
}
that is called from the glue function. The intlist is returned
like it comes out of this function.

Now, when I try the following:
lis = ldw.ldw("Hol",["Kohl","Pfohl"])
a = max(lis)
(ldw.ldw being the glue function), I get
Traceback (innermost last):
File "zw.py", line 3, in ?
a = max(lis)
TypeError: argument 2: expected string, list found
(that's python 1.5.2, FWIW). Odd, isn't it? Why
should max insist on a string?

But it gets better than that:
When I do
lis = ldw.ldw("Hol",["Kohl","Pfohl"])
print type(lis)
a = max(lis)
suddenly everything is fine, and a has
the correct value, etc.

Now, I strongly suspect that in the C code I did something I
should not do. The only problem is that I can't see what
that might be. Of course, I'd also be interested in knowing
why a print statement appearently fixes whatever sacrileg I
commited...

Markus
Extension module mystery [ In reply to ]
Markus Demleitner <msdemlei@tucana.harvard.edu> wrote:
> Now, when I try the following:
> lis = ldw.ldw("Hol",["Kohl","Pfohl"])
> a = max(lis)
> (ldw.ldw being the glue function), I get
> Traceback (innermost last):
> File "zw.py", line 3, in ?
> a = max(lis)
> TypeError: argument 2: expected string, list found
> (that's python 1.5.2, FWIW). Odd, isn't it? Why
> should max insist on a string?

maybe it isn't max that generates that error;
instead, it looks like you've missed to test for
a Python exception somewhere (if you ignore
errors, and don't call PyErr_Clear() to clean up,
Python may raise them later...)

could it be that you forgot to change the glue
function to look for an object rather than a
string?

</F>