1

I am creating C-extensions for Python3. However, I keep getting errors when trying to make a list object.

I have read the documentation and tried various ways of creating a

How do I properly create a list?

Code (Attempt 1)

PyObject *listall;
PyObject *listall = Py_BuildValue("[sss]", "pka", "pkb", "iselement");

Error (Attempt 1)

./lib/clib-src/pychemistry.c:37:21: error: initializer element is not constant
 PyObject *listall = Py_BuildValue("[sss]", "pka", "pkb", "three");

Code (Attempt 2)

PyObject *list;
PyObject *list = PyList_New(3);
PyList_SetItem(list, (Py_ssize_t)0, PyUnicode_FromString("pka"));
PyList_SetItem(list, (Py_ssize_t)1, PyUnicode_FromString("pkb"));
PyList_SetItem(list, (Py_ssize_t)2, PyUnicode_FromString("iselement"));

Error (Attempt 2)

./lib/clib-src/pychemistry.c:39:18: error: initializer element is not constant
 PyObject *list = PyList_New(3);
                  ^
./lib/clib-src/pychemistry.c:40:22: error: expected ‘)’ before ‘(’ token
 PyList_SetItem(list, (Py_ssize_t)0, PyUnicode_FromString("pka"));
                      ^
./lib/clib-src/pychemistry.c:41:22: error: expected ‘)’ before ‘(’ token
 PyList_SetItem(list, (Py_ssize_t)1, PyUnicode_FromString("pkb"));
                      ^
./lib/clib-src/pychemistry.c:42:22: error: expected ‘)’ before ‘(’ token
 PyList_SetItem(list, (Py_ssize_t)2, PyUnicode_FromString("iselement"));
2
  • Why are you defining your variable twice? Commented Dec 25, 2015 at 17:27
  • I was hoping that using "PyObject *list;" before setting the value would help. However, it makes no difference w/o it. Commented Dec 25, 2015 at 17:32

1 Answer 1

2

Next time, please post a Minimal, Complete, and Verifiable example.

From your code, it looks like you're attempting to store the result of Py_BuildValue/PyList_New in an object with static storage duration. This is not allowed in C, as only the results of constant expressions are allowed to be assigned to such objects.

What you probably want to do is put your code inside a function, like so:

PyObject *create_list(void)
{
    PyObject *listall;
    // NOTE: you don't need to specify the object's type again,
    // since it was already defined above
    listall = Py_BuildValue("[sss]", "pka", "pkb", "iselement");
    return listall;
}
Sign up to request clarification or add additional context in comments.

Comments

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.