Commit 33e44bea authored by Kevin Modzelewski's avatar Kevin Modzelewski

Have dict.__getitem__ check __missing__

This is needed for defaultdict
parent f2fcdc4f
......@@ -280,7 +280,13 @@ extern "C" PyObject* PyObject_GetItem(PyObject* o, PyObject* key) noexcept {
}
extern "C" int PyObject_SetItem(PyObject* o, PyObject* key, PyObject* v) noexcept {
Py_FatalError("unimplemented");
try {
setitem(o, key, v);
return 0;
} catch (ExcInfo e) {
setCAPIException(e);
return -1;
}
}
extern "C" int PyObject_DelItem(PyObject* o, PyObject* key) noexcept {
......
......@@ -174,6 +174,15 @@ Box* dictGetitem(BoxedDict* self, Box* k) {
auto it = self->d.find(k);
if (it == self->d.end()) {
// Try calling __missing__ if this is a subclass
if (self->cls != dict_cls) {
static const std::string missing("__missing__");
Box* r = callattr(self, &missing, CallattrFlags({.cls_only = true, .null_on_nonexistent = true }),
ArgPassSpec(1), k, NULL, NULL, NULL, NULL);
if (r)
return r;
}
raiseExcHelper(KeyError, k);
}
......
......@@ -7,3 +7,8 @@ for i in xrange(30):
print o
print collections.deque().maxlen
d = collections.defaultdict(lambda: [])
print d[1]
d[2].append(3)
print sorted(d.items())
......@@ -9,3 +9,11 @@ print d.items()
print list(d.iterkeys())
print list(d.itervalues())
print list(d.iteritems())
class DictWithMissing(dict):
def __missing__(self, key):
print key
return key
d = DictWithMissing()
print d[5]
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment