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

Skip to content

Commit ef67111

Browse files
committed
Fix this right for has_key(). This required adding tp_as_sequence.
1 parent e014a13 commit ef67111

1 file changed

Lines changed: 34 additions & 13 deletions

File tree

Modules/dbmmodule.c

Lines changed: 34 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -205,20 +205,42 @@ dbm_keys(register dbmobject *dp, PyObject *unused)
205205
return v;
206206
}
207207

208-
static PyObject *
209-
dbm_contains(register dbmobject *dp, PyObject *args)
208+
static int
209+
dbm_contains(PyObject *self, PyObject *arg)
210210
{
211+
dbmobject *dp = (dbmobject *)self;
211212
datum key, val;
212-
int tmp_size;
213-
214-
if (!PyArg_ParseTuple(args, "s#:__contains__", &key.dptr, &tmp_size))
215-
return NULL;
216-
key.dsize = tmp_size;
217-
check_dbmobject_open(dp);
213+
214+
if ((dp)->di_dbm == NULL) {
215+
PyErr_SetString(DbmError,
216+
"DBM object has already been closed");
217+
return -1;
218+
}
219+
if (!PyString_Check(arg)) {
220+
PyErr_Format(PyExc_TypeError,
221+
"dbm key must be string, not %.100s",
222+
arg->ob_type->tp_name);
223+
return -1;
224+
}
225+
key.dptr = PyString_AS_STRING(arg);
226+
key.dsize = PyString_GET_SIZE(arg);
218227
val = dbm_fetch(dp->di_dbm, key);
219-
return PyInt_FromLong(val.dptr != NULL);
228+
return val.dptr != NULL;
220229
}
221230

231+
static PySequenceMethods dbm_as_sequence = {
232+
0, /* sq_length */
233+
0, /* sq_concat */
234+
0, /* sq_repeat */
235+
0, /* sq_item */
236+
0, /* sq_slice */
237+
0, /* sq_ass_item */
238+
0, /* sq_ass_slice */
239+
dbm_contains, /* sq_contains */
240+
0, /* sq_inplace_concat */
241+
0, /* sq_inplace_repeat */
242+
};
243+
222244
static PyObject *
223245
dbm_get(register dbmobject *dp, PyObject *args)
224246
{
@@ -277,8 +299,6 @@ static PyMethodDef dbm_methods[] = {
277299
"close()\nClose the database."},
278300
{"keys", (PyCFunction)dbm_keys, METH_NOARGS,
279301
"keys() -> list\nReturn a list of all keys in the database."},
280-
{"__contains__",(PyCFunction)dbm_contains, METH_VARARGS,
281-
"__contains__(key} -> boolean\True iff key is in the database."},
282302
{"get", (PyCFunction)dbm_get, METH_VARARGS,
283303
"get(key[, default]) -> value\n"
284304
"Return the value for key if present, otherwise default."},
@@ -308,7 +328,7 @@ static PyTypeObject Dbmtype = {
308328
0, /*tp_compare*/
309329
0, /*tp_repr*/
310330
0, /*tp_as_number*/
311-
0, /*tp_as_sequence*/
331+
&dbm_as_sequence, /*tp_as_sequence*/
312332
&dbm_as_mapping, /*tp_as_mapping*/
313333
};
314334

@@ -353,7 +373,8 @@ PyMODINIT_FUNC
353373
initdbm(void) {
354374
PyObject *m, *d, *s;
355375

356-
Dbmtype.ob_type = &PyType_Type;
376+
if (PyType_Ready(&Dbmtype) < 0)
377+
return;
357378
m = Py_InitModule("dbm", dbmmodule_methods);
358379
if (m == NULL)
359380
return;

0 commit comments

Comments
 (0)