1

I am writing C extensions for python.

I want to know how to add a C object to python list using PyList_SetItem. For example,

I have a C object.

Atom *a = (Atom *)(PyTuple_GET_ITEM(tmp2, 0));

I made a list:

PyObject* MyList = PyList_New(3);

I am not sure what the third argument must be in the following statement.

PyObject_SetItem(MyList, 0, a);

Also how do I return this list of C objects to python.

1 Answer 1

4

The third argument to PyList_SetItem is the Python Object to be added to the list, which is usually converted from a C type, as in this simple example:

/* This adds one to each item in a list.  For example:
        alist = [1,2,3,4,5]
        RefArgs.MyFunc(alist)
*/
static PyObject * MyFunc(PyObject *self, PyObject *args)
{
   PyObject * ArgList;
   int i;

   PyArg_ParseTuple(args, "O!", &PyList_Type, &ArgList));

   for (i = 0; i < PyList_Size(ArgList); i++)
   {
      PyObject * PyValue;
      long iValue;

      PyValue = PyList_GetItem(ArgList, i);

      /* Add 1 to each item in the list (trivial, I know) */
      iValue = PyLong_AsLong(PyValue) + 1;

      /* SETTING THE ITEM */
      iRetn = PyList_SetItem(ArgList, i, PyLong_FromLong(iValue));

      if (iRetn == -1) Py_RETURN_FALSE;
   }

   Py_RETURN_TRUE;
}

PyObject_SetItem is similar. The difference is that PyList_SetItem steals the reference, but PyObject_SetItem only borrows it. PyObject_SetItem cannot be used with an immutable object, like a tuple.

Sign up to request clarification or add additional context in comments.

3 Comments

What is the equivalent function for PyLong_FromLong if I want to add a C object (Atom) to the list?
Not to be nitpicking, but this answer doesn't add an item to a list. It takes an existing list and updates the values.
@Jiminion: you are right, that is what PyList_SetItem does. The OP specifically asked for this API, but of course it does not append: PyList_Append() is required for that (or PyList_Insert() could be used).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.