summaryrefslogtreecommitdiffstats
path: root/Objects
diff options
context:
space:
mode:
authorGuido van Rossum <guido@python.org>2001-04-20 16:50:40 (GMT)
committerGuido van Rossum <guido@python.org>2001-04-20 16:50:40 (GMT)
commit0dbb4fba4c59741466ac18eeb946ca56989717d4 (patch)
treec7c0fe7c20813024cb023075b597fee3c99abd64 /Objects
parent78fe5308b427298a2bb3c80c1d0f6117d18fcf62 (diff)
downloadcpython-0dbb4fba4c59741466ac18eeb946ca56989717d4.zip
cpython-0dbb4fba4c59741466ac18eeb946ca56989717d4.tar.gz
cpython-0dbb4fba4c59741466ac18eeb946ca56989717d4.tar.bz2
Implement, test and document "key in dict" and "key not in dict".
I know some people don't like this -- if it's really controversial, I'll take it out again. (If it's only Alex Martelli who doesn't like it, that doesn't count as "real controversial" though. :-) That's why this is a separate checkin from the iterators stuff I'm about to check in next.
Diffstat (limited to 'Objects')
-rw-r--r--Objects/dictobject.c36
1 files changed, 35 insertions, 1 deletions
diff --git a/Objects/dictobject.c b/Objects/dictobject.c
index cc10db0..d00e326 100644
--- a/Objects/dictobject.c
+++ b/Objects/dictobject.c
@@ -1292,6 +1292,40 @@ dict_getattr(dictobject *mp, char *name)
return Py_FindMethod(mapp_methods, (PyObject *)mp, name);
}
+static int
+dict_contains(dictobject *mp, PyObject *key)
+{
+ long hash;
+
+#ifdef CACHE_HASH
+ if (!PyString_Check(key) ||
+ (hash = ((PyStringObject *) key)->ob_shash) == -1)
+#endif
+ {
+ hash = PyObject_Hash(key);
+ if (hash == -1)
+ return -1;
+ }
+ return (mp->ma_size != 0
+ && (mp->ma_lookup)(mp, key, hash)->me_value != NULL);
+}
+
+staticforward PyObject *dictiter_new(dictobject *);
+
+/* Hack to implement "key in dict" */
+static PySequenceMethods dict_as_sequence = {
+ 0, /* sq_length */
+ 0, /* sq_concat */
+ 0, /* sq_repeat */
+ 0, /* sq_item */
+ 0, /* sq_slice */
+ 0, /* sq_ass_item */
+ 0, /* sq_ass_slice */
+ (objobjproc)dict_contains, /* sq_contains */
+ 0, /* sq_inplace_concat */
+ 0, /* sq_inplace_repeat */
+};
+
PyTypeObject PyDict_Type = {
PyObject_HEAD_INIT(&PyType_Type)
0,
@@ -1305,7 +1339,7 @@ PyTypeObject PyDict_Type = {
(cmpfunc)dict_compare, /* tp_compare */
(reprfunc)dict_repr, /* tp_repr */
0, /* tp_as_number */
- 0, /* tp_as_sequence */
+ &dict_as_sequence, /* tp_as_sequence */
&dict_as_mapping, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */