TOC

Python 源码学习 07: list

cpython/Include/cpython/tupleobject.h

INIT_TYPE(&PyList_Type, "list");
SETBUILTIN("list", &PyList_Type);

PyTypeObject PyList_Type 的定义在 Objects/listobject.c 中。

成员方法

相关的方法在 #define LIST_.+_METHODDEF 的定义中,比如 extend 方法:

#define LIST_APPEND_METHODDEF    \
    {"append", (PyCFunction)list_append, METH_O, list_append__doc__},

static PyObject *
list_append(PyListObject *self, PyObject *object)
/*[clinic end generated code: output=7c096003a29c0eae input=43a3fe48a7066e91]*/
{
    if (app1(self, object) == 0)
        Py_RETURN_NONE;
    return NULL;
}

static int
app1(PyListObject *self, PyObject *v)
{
    Py_ssize_t n = PyList_GET_SIZE(self);

    assert (v != NULL);
    if (n == PY_SSIZE_T_MAX) {
        PyErr_SetString(PyExc_OverflowError,
            "cannot add more objects to list");
        return -1;
    }

    if (list_resize(self, n+1) < 0)
        return -1;

    Py_INCREF(v);
    PyList_SET_ITEM(self, n, v);
    return 0;
}