summaryrefslogtreecommitdiffstats
path: root/Objects/dictobject.c
diff options
context:
space:
mode:
authorBarry Warsaw <barry@python.org>1997-10-06 17:49:20 (GMT)
committerBarry Warsaw <barry@python.org>1997-10-06 17:49:20 (GMT)
commitc38c5da5d0ce35442e859d64e6cfa734688a470e (patch)
tree31a597dcfd093364cceeaeed57e4756ac06c2c9f /Objects/dictobject.c
parent596db3161c8cf0a492f5613cb5721b6c12c1dceb (diff)
downloadcpython-c38c5da5d0ce35442e859d64e6cfa734688a470e.zip
cpython-c38c5da5d0ce35442e859d64e6cfa734688a470e.tar.gz
cpython-c38c5da5d0ce35442e859d64e6cfa734688a470e.tar.bz2
dict_get(): New method for item access with different semantics than
__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.
Diffstat (limited to 'Objects/dictobject.c')
-rw-r--r--Objects/dictobject.c38
1 files changed, 38 insertions, 0 deletions
diff --git a/Objects/dictobject.c b/Objects/dictobject.c
index 3362655..e5a4610 100644
--- a/Objects/dictobject.c
+++ b/Objects/dictobject.c
@@ -953,6 +953,43 @@ dict_has_key(mp, args)
}
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;
PyObject *args;
@@ -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 */
};