]> granicus.if.org Git - python/commitdiff
dict_get(): New method for item access with different semantics than
authorBarry Warsaw <barry@python.org>
Mon, 6 Oct 1997 17:49:20 +0000 (17:49 +0000)
committerBarry Warsaw <barry@python.org>
Mon, 6 Oct 1997 17:49:20 +0000 (17:49 +0000)
__getitem__().  This method never raises an exception; if the key is
not in the dictionary, the second (optional) argument is returned.  If
the second argument is not provided and the key is missing, None is
returned.

mapp_methods: added "get" method.

Objects/dictobject.c

index 3362655b4cadd296e20cb89ac81f52be4bcf7673..e5a461031ebb53a58986d20f6fe1569dd5b7f99d 100644 (file)
@@ -952,6 +952,43 @@ dict_has_key(mp, args)
        return PyInt_FromLong(ok);
 }
 
+static PyObject *
+dict_get(mp, args)
+       register dictobject *mp;
+       PyObject *args;
+{
+       PyObject *key;
+       PyObject *failobj = NULL;
+       PyObject *val = NULL;
+       long hash;
+
+       if (mp->ma_table == NULL)
+               goto finally;
+
+       if (!PyArg_ParseTuple(args, "O|O", &key, &failobj))
+               return NULL;
+
+       if (failobj == NULL)
+               failobj = Py_None;
+
+#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;
+       Py_INCREF(val);
+       return val;
+}
+
+
 static PyObject *
 dict_clear(mp, args)
        register dictobject *mp;
@@ -972,6 +1009,7 @@ static PyMethodDef mapp_methods[] = {
        {"update",      (PyCFunction)dict_update},
        {"clear",       (PyCFunction)dict_clear},
        {"copy",        (PyCFunction)dict_copy},
+       {"get",         (PyCFunction)dict_get, 1},
        {NULL,          NULL}           /* sentinel */
 };