mirror of
https://github.com/python/cpython.git
synced 2025-12-10 19:10:59 +00:00
Barry's patch to implement the new setdefault() method.
This commit is contained in:
parent
2b042ded19
commit
164452cec4
2 changed files with 40 additions and 0 deletions
|
|
@ -34,3 +34,7 @@ class UserDict:
|
||||||
self.data[k] = v
|
self.data[k] = v
|
||||||
def get(self, key, failobj=None):
|
def get(self, key, failobj=None):
|
||||||
return self.data.get(key, failobj)
|
return self.data.get(key, failobj)
|
||||||
|
def setdefault(self, key, failobj=None):
|
||||||
|
if not self.data.has_key(key):
|
||||||
|
self.data[key] = failobj
|
||||||
|
return self.data[key]
|
||||||
|
|
|
||||||
|
|
@ -949,6 +949,41 @@ dict_get(register dictobject *mp, PyObject *args)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static PyObject *
|
||||||
|
dict_setdefault(register dictobject *mp, PyObject *args)
|
||||||
|
{
|
||||||
|
PyObject *key;
|
||||||
|
PyObject *failobj = Py_None;
|
||||||
|
PyObject *val = NULL;
|
||||||
|
long hash;
|
||||||
|
|
||||||
|
if (!PyArg_ParseTuple(args, "O|O:setdefault", &key, &failobj))
|
||||||
|
return NULL;
|
||||||
|
if (mp->ma_table == NULL)
|
||||||
|
goto finally;
|
||||||
|
|
||||||
|
#ifdef CACHE_HASH
|
||||||
|
if (!PyString_Check(key) ||
|
||||||
|
(hash = ((PyStringObject *) key)->ob_shash) == -1)
|
||||||
|
#endif
|
||||||
|
{
|
||||||
|
hash = PyObject_Hash(key);
|
||||||
|
if (hash == -1)
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
val = lookdict(mp, key, hash)->me_value;
|
||||||
|
|
||||||
|
finally:
|
||||||
|
if (val == NULL) {
|
||||||
|
val = failobj;
|
||||||
|
if (PyDict_SetItem((PyObject*)mp, key, failobj))
|
||||||
|
val = NULL;
|
||||||
|
}
|
||||||
|
Py_XINCREF(val);
|
||||||
|
return val;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
static PyObject *
|
static PyObject *
|
||||||
dict_clear(register dictobject *mp, PyObject *args)
|
dict_clear(register dictobject *mp, PyObject *args)
|
||||||
{
|
{
|
||||||
|
|
@ -993,6 +1028,7 @@ static PyMethodDef mapp_methods[] = {
|
||||||
{"clear", (PyCFunction)dict_clear},
|
{"clear", (PyCFunction)dict_clear},
|
||||||
{"copy", (PyCFunction)dict_copy},
|
{"copy", (PyCFunction)dict_copy},
|
||||||
{"get", (PyCFunction)dict_get, METH_VARARGS},
|
{"get", (PyCFunction)dict_get, METH_VARARGS},
|
||||||
|
{"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS},
|
||||||
{NULL, NULL} /* sentinel */
|
{NULL, NULL} /* sentinel */
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue