]> granicus.if.org Git - python/commitdiff
Barry's patch to implement the new setdefault() method.
authorGuido van Rossum <guido@python.org>
Tue, 8 Aug 2000 16:12:54 +0000 (16:12 +0000)
committerGuido van Rossum <guido@python.org>
Tue, 8 Aug 2000 16:12:54 +0000 (16:12 +0000)
Lib/UserDict.py
Objects/dictobject.c

index 3c484157718e1cfb013d0087dbb3c04201ef8609..9b6e73b50f26428eb329482674d713b99a3bd5d6 100644 (file)
@@ -34,3 +34,7 @@ class UserDict:
                 self.data[k] = v
     def get(self, key, failobj=None):
         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]
index 4fafb8a963b03c4346e15f416d6ebb779d52f862..ddd8eb8b69d46a0bbcc5ed8847a4628ff6003dba 100644 (file)
@@ -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 *
 dict_clear(register dictobject *mp, PyObject *args)
 {
@@ -993,6 +1028,7 @@ static PyMethodDef mapp_methods[] = {
        {"clear",       (PyCFunction)dict_clear},
        {"copy",        (PyCFunction)dict_copy},
        {"get",         (PyCFunction)dict_get,          METH_VARARGS},
+       {"setdefault",  (PyCFunction)dict_setdefault,   METH_VARARGS},
        {NULL,          NULL}           /* sentinel */
 };