Skip to content

adding the get method for lists #131077

@vomas7

Description

@vomas7

Hi! The topic of creating a secure get method for lists has been discussed several times in the community. I suggest the following implementation

Proposal:

static PyObject *
list_get(PyListObject *self, PyObject *args) {
    Py_ssize_t index;
    PyObject *default_value = Py_None;

    if (!PyArg_ParseTuple(args, "n|O:get", &index, &default_value)) {
        return NULL;
    }

    if (index < 0 || index >= Py_SIZE(self)) {
        Py_INCREF(default_value);
        return default_value;
    }

    Py_INCREF(self->ob_item[index]);
    return self->ob_item[index];
}

implementation in python:

l = [1, 2, 3]
l.get(0)
1
print(type(p))
<class 'NoneType'>
l.get(4, 'False')
'False'
l.get(4, False)
False

Has this already been discussed elsewhere?

Discussed on the python forum

Links to previous discussion of this feature:

previous discussion

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions