- Patch 1433928:
- The copy module now "copies" function objects (as atomic objects).
- dict.__getitem__ now looks for a __missing__ hook before raising
KeyError.
- Added a new type, defaultdict, to the collections module.
This uses the new __missing__ hook behavior added to dict (see above).
diff --git a/Objects/dictobject.c b/Objects/dictobject.c
index f5e5320..2254762 100644
--- a/Objects/dictobject.c
+++ b/Objects/dictobject.c
@@ -882,8 +882,22 @@
return NULL;
}
v = (mp->ma_lookup)(mp, key, hash) -> me_value;
- if (v == NULL)
+ if (v == NULL) {
+ if (!PyDict_CheckExact(mp)) {
+ /* Look up __missing__ method if we're a subclass. */
+ static PyObject *missing_str = NULL;
+ if (missing_str == NULL)
+ missing_str =
+ PyString_InternFromString("__missing__");
+ PyObject *missing = _PyType_Lookup(mp->ob_type,
+ missing_str);
+ if (missing != NULL)
+ return PyObject_CallFunctionObjArgs(missing,
+ (PyObject *)mp, key, NULL);
+ }
PyErr_SetObject(PyExc_KeyError, key);
+ return NULL;
+ }
else
Py_INCREF(v);
return v;