Skip to content

Commit eaa1e11

Browse files
author
Krasnopoliskij.IA
committed
gh-131077: adding a get method for lists with a dictionary-like implementatio
1 parent 425e0af commit eaa1e11

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

Objects/listobject.c

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3497,6 +3497,24 @@ list___sizeof___impl(PyListObject *self)
34973497
static PyObject *list_iter(PyObject *seq);
34983498
static PyObject *list_subscript(PyObject*, PyObject*);
34993499

3500+
static PyObject *
3501+
list_get(PyListObject *self, PyObject *args) {
3502+
Py_ssize_t index;
3503+
PyObject *default_value = Py_None;
3504+
3505+
if (!PyArg_ParseTuple(args, "n|O:get", &index, &default_value)) {
3506+
return NULL;
3507+
}
3508+
3509+
if (index < 0 || index >= Py_SIZE(self)) {
3510+
Py_INCREF(default_value);
3511+
return default_value;
3512+
}
3513+
3514+
Py_INCREF(self->ob_item[index]);
3515+
return self->ob_item[index];
3516+
}
3517+
35003518
static PyMethodDef list_methods[] = {
35013519
{"__getitem__", list_subscript, METH_O|METH_COEXIST,
35023520
PyDoc_STR("__getitem__($self, index, /)\n--\n\nReturn self[index].")},
@@ -3513,6 +3531,8 @@ static PyMethodDef list_methods[] = {
35133531
LIST_COUNT_METHODDEF
35143532
LIST_REVERSE_METHODDEF
35153533
LIST_SORT_METHODDEF
3534+
{"get", list_get, METH_VARARGS,
3535+
PyDoc_STR("get(self, index, default=None)\n--\n\nReturn item at index or default value if index is out of range.")},
35163536
{"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
35173537
{NULL, NULL} /* sentinel */
35183538
};

0 commit comments

Comments
 (0)