Extension module mystery

Markus Demleitner msdemlei at tucana.harvard.edu
Mon Jul 26 15:53:45 EDT 1999


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





More information about the Python-list mailing list