Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c38c5da

Browse files
committed
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.
1 parent 596db31 commit c38c5da

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

Objects/dictobject.c

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -952,6 +952,43 @@ dict_has_key(mp, args)
952952
return PyInt_FromLong(ok);
953953
}
954954

955+
static PyObject *
956+
dict_get(mp, args)
957+
register dictobject *mp;
958+
PyObject *args;
959+
{
960+
PyObject *key;
961+
PyObject *failobj = NULL;
962+
PyObject *val = NULL;
963+
long hash;
964+
965+
if (mp->ma_table == NULL)
966+
goto finally;
967+
968+
if (!PyArg_ParseTuple(args, "O|O", &key, &failobj))
969+
return NULL;
970+
971+
if (failobj == NULL)
972+
failobj = Py_None;
973+
974+
#ifdef CACHE_HASH
975+
if (!PyString_Check(key) ||
976+
(hash = ((PyStringObject *) key)->ob_shash) == -1)
977+
#endif
978+
{
979+
hash = PyObject_Hash(key);
980+
if (hash == -1)
981+
return NULL;
982+
}
983+
val = lookdict(mp, key, hash)->me_value;
984+
finally:
985+
if (val == NULL)
986+
val = failobj;
987+
Py_INCREF(val);
988+
return val;
989+
}
990+
991+
955992
static PyObject *
956993
dict_clear(mp, args)
957994
register dictobject *mp;
@@ -972,6 +1009,7 @@ static PyMethodDef mapp_methods[] = {
9721009
{"update", (PyCFunction)dict_update},
9731010
{"clear", (PyCFunction)dict_clear},
9741011
{"copy", (PyCFunction)dict_copy},
1012+
{"get", (PyCFunction)dict_get, 1},
9751013
{NULL, NULL} /* sentinel */
9761014
};
9771015

0 commit comments

Comments
 (0)