diff --git a/python/collections.py b/python/collections.py index 0f526d4d..4e88198d 100644 --- a/python/collections.py +++ b/python/collections.py @@ -117,3 +117,5 @@ class defaultdict: def items(self): return self._a.items() + def pop(self, key): + return self._a.pop(key) diff --git a/src/pocketpy.h b/src/pocketpy.h index 361cf6a3..e71febc1 100644 --- a/src/pocketpy.h +++ b/src/pocketpy.h @@ -898,6 +898,14 @@ inline void init_builtins(VM* _vm) { self.erase(key); }); + _vm->bind_method<1>("dict", "pop", [](VM* vm, ArgsView args) { + Dict& self = _CAST(Dict&, args[0]); + PyObject* value = self.try_get(args[1]); + if(value == nullptr) vm->KeyError(args[1]); + self.erase(args[1]); + return value; + }); + _vm->bind__contains__(_vm->tp_dict, [](VM* vm, PyObject* obj, PyObject* key) { Dict& self = _CAST(Dict&, obj); return self.contains(key); diff --git a/tests/07_dict.py b/tests/07_dict.py index e95c1953..def4359c 100644 --- a/tests/07_dict.py +++ b/tests/07_dict.py @@ -47,4 +47,9 @@ assert d1 == d2 assert d1 != d3 a = dict([(1, 2), (3, 4)]) -assert a == {1: 2, 3: 4} \ No newline at end of file +assert a == {1: 2, 3: 4} + +assert a.pop(1) == 2 +assert a == {3: 4} +assert a.pop(3) == 4 +assert a == {} \ No newline at end of file