PyListObject & C Modules

Joshua Gramlich jggramlich at yahoo.com
Thu Sep 5 14:14:42 EDT 2002


Okay...what I have now:

##############################code
block#################################

#include "Python.h"
#include <stdio.h>

static PyObject *ErrorObject;
#define onError(message) \
    { PyErr_SetString(ErrorObject, message); return NULL; }

PyObject*
get_first_elem(PyObject *unused, PyObject *args)
{
  PyObject *list;
  PyObject *first;
  PyObject *result;

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

  if(!PyList_Check(list)) {
    PyErr_SetString(PyExc_TypeError, "get_first_elem expects a list");
    return NULL;
  }

  if(PyList_Size(list) == 0){
    PyErr_SetString(PyExc_ValueError, "empty lists not allowed");
    return NULL;
  }

  first = PyList_GetItem(list, 0);
  result = PyList_New(1);
  if (!result) return NULL;
  Py_INCREF(first);

  if (PyList_SetItem(result, 0, first) != 0) {
    Py_DECREF(first);
    Py_DECREF(result);
    result = NULL;
  }
  return result;
}

static struct PyMethodDef slist_methods[] = {
 {"getfstelm",     get_first_elem,     1},
 {NULL,                NULL}
};

void initslist()
{
    PyObject *m, *d;

    m = Py_InitModule("slist", slist_methods);

    d = PyModule_GetDict(m);
    ErrorObject = Py_BuildValue("s", "slist.error");
    PyDict_SetItemString(d, "error", ErrorObject);

    if (PyErr_Occurred())
        Py_FatalError("cannot initialize module slist");
}

##########################end code block############################

I have been reading the tutorial (amongst other things), and yes, I
should
probably have eventually caught the ADDREF bit.  The above compiles
fine and what-not, but when I run it via this:

############### hello.py #####################

stuff = 7,8,8,23,222,12
print(stuff)
pidge = slist.getfstelm(stuff)
print(pidge)

##############################################

I get this:

[d0ora3 ~/work/grid_query/test]$ python hello.py 

(7, 8, 8, 23, 222, 12)
Traceback (most recent call last):
  File "hello.py", line 25, in ?
    pidge = slist.getfstelm(stuff)
TypeError: argument 1 must be impossible<bad format char>, not tuple
[d0ora3 ~/work/grid_query/test]$ 



Now, if "stuff" is changed to "[7,8,8,23,222,12]" then the TypeError
ends with "not list" instead of "not tuple" and so on for ints and
strings.

Thoughts?



More information about the Python-list mailing list