Python lists ans sequence protocol from C API

Matjaz surfmatj at email.si
Wed Sep 22 08:53:40 EDT 2004


Dear all,

I have run into a problem using python lists and sequence protocol.
The first code snippet uses explicit list operations and works fine.


PyObject *argseq, *ov;
int i, v, len;

len = 2;
argseq = PyList_New(len);
for (i=0; i<len; i++) {
      ov = PyInt_FromLong(i);
      printf("Index %d. Success %d.\n", i, PyList_SetItem(argseq, i, ov));
}
for (i=0; i<len; i++) {
      ov = PyList_GetItem(argseq,i);
      v = PyInt_AsLong(ov);
      printf("Index %d. Read %d.\n", i, v);
}

Output:

Index 0. Success 0.
Index 1. Success 0.
Index 0. Read 0.
Index 1. Read 1.

Argseq results in a python list [0, 1], as it should.
However, if I change the above code to use sequence protocol
for GetItem and SetItem (see below), the program fails when calling
PySequence_SetItem with the following error message:
"Unhandled exception at 0x1e04ed1a in python.exe:
0xC0000005: Access violation reading location 0x00000000."
Could it be that basic lists do not support sequence protocol?
Or am I missing something? I'm using Python 2.3.4 on Windows XP.

PyObject *argseq, *ov;
int i, v, len;

len = 2;
argseq = PyList_New(len);
for (i=0; i<len; i++) {
     ov = PyInt_FromLong(i);
     printf("Index %d. Success %d.\n", i, PySequence_SetItem(argseq, i, ov));
}
for (i=0; i<len; i++) {
     ov = PySequence_GetItem(argseq,i);
     v = PyInt_AsLong(ov);
     printf("Index %d. Read %d.\n", i, v);
}

Why would I wish to use sequence with basic lists protocol? Because my code should
also deal with other sequence types, possibly subclassed from python lists.

Thanks,

Matjaz.



More information about the Python-list mailing list