Commit 88b14539 authored by Leandro Lameiro's avatar Leandro Lameiro

Add dict.popitem + tests

parent e2a1eecc
...@@ -171,6 +171,22 @@ Box* dictPop(BoxedDict* self, Box* k, Box* d) { ...@@ -171,6 +171,22 @@ Box* dictPop(BoxedDict* self, Box* k, Box* d) {
return rtn; return rtn;
} }
Box* dictPopitem(BoxedDict* self) {
RELEASE_ASSERT(self->cls == dict_cls, "");
auto it = self->d.begin();
if (it == self->d.end()) {
raiseExcHelper(KeyError, "popitem(): dictionary is empty");
}
Box* key = it->first;
Box* value = it->second;
self->d.erase(it);
auto rtn = new BoxedTuple({ key, value });
return rtn;
}
Box* dictGet(BoxedDict* self, Box* k, Box* d) { Box* dictGet(BoxedDict* self, Box* k, Box* d) {
assert(self->cls == dict_cls); assert(self->cls == dict_cls);
...@@ -337,6 +353,8 @@ void setupDict() { ...@@ -337,6 +353,8 @@ void setupDict() {
dict_cls->giveAttr("iterkeys", dict_cls->getattr("__iter__")); dict_cls->giveAttr("iterkeys", dict_cls->getattr("__iter__"));
dict_cls->giveAttr("pop", new BoxedFunction(boxRTFunction((void*)dictPop, UNKNOWN, 3, 1, false, false), { NULL })); dict_cls->giveAttr("pop", new BoxedFunction(boxRTFunction((void*)dictPop, UNKNOWN, 3, 1, false, false), { NULL }));
dict_cls->giveAttr("popitem", new BoxedFunction(boxRTFunction((void*)dictPopitem, BOXED_TUPLE, 1)));
dict_cls->giveAttr("get", new BoxedFunction(boxRTFunction((void*)dictGet, UNKNOWN, 3, 1, false, false), { None })); dict_cls->giveAttr("get", new BoxedFunction(boxRTFunction((void*)dictGet, UNKNOWN, 3, 1, false, false), { None }));
......
...@@ -146,3 +146,20 @@ print d.has_key(1) ...@@ -146,3 +146,20 @@ print d.has_key(1)
print d.has_key(42) print d.has_key(42)
print d.has_key('a') print d.has_key('a')
print d.has_key('b') print d.has_key('b')
# popitem - actual order is implementation defined
d = {1:2, 3:4, 'a': 5}
l = []
l.append(d.popitem())
l.append(d.popitem())
l.append(d.popitem())
print sorted(l)
try:
d.popitem()
assert 0
except KeyError, e:
print 'ok'
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