From 348f19b415ce14da9dc48ab6ab6c34071ae4f6f0 Mon Sep 17 00:00:00 2001 From: Kyle Ellrott Date: Thu, 12 Jan 2023 13:06:51 -0800 Subject: [PATCH 1/2] Adding __delitem__ to dict. Enables the 'del' command to delete items from a dict --- py/dict.go | 12 ++++++++++++ py/tests/dict.py | 6 ++++++ 2 files changed, 18 insertions(+) diff --git a/py/dict.go b/py/dict.go index 10c2d33f..cab359b1 100644 --- a/py/dict.go +++ b/py/dict.go @@ -189,6 +189,18 @@ func (d StringDict) M__getitem__(key Object) (Object, error) { return nil, ExceptionNewf(KeyError, "%v", key) } +func (d StringDict) M__delitem__(key Object) (Object, error) { + str, ok := key.(String) + if ok { + _, ok := d[string(str)] + if ok { + delete(d, string(str)) + return None, nil + } + } + return nil, ExceptionNewf(KeyError, "%v", key) +} + func (d StringDict) M__setitem__(key, value Object) (Object, error) { str, ok := key.(String) if !ok { diff --git a/py/tests/dict.py b/py/tests/dict.py index d6140e47..a62a49ed 100644 --- a/py/tests/dict.py +++ b/py/tests/dict.py @@ -46,6 +46,12 @@ assert v == 5.5 assertRaises(TypeError, a.items, 'a') +doc="del" +a = {'hello': 'world', 'hi': 'there'} +del a["hello"] +assert not a.__contains__('hello') +assert a.__contains__('hi') + doc="__contain__" a = {'hello': 'world'} assert a.__contains__('hello') From c89f95cc09a80afe30315a392ee7066303ebb2e1 Mon Sep 17 00:00:00 2001 From: Kyle Ellrott Date: Fri, 13 Jan 2023 13:16:10 -0800 Subject: [PATCH 2/2] Adding more exception and testing to dict del command --- py/dict.go | 15 ++++++++------- py/tests/dict.py | 4 ++++ 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/py/dict.go b/py/dict.go index cab359b1..f0aa938c 100644 --- a/py/dict.go +++ b/py/dict.go @@ -191,14 +191,15 @@ func (d StringDict) M__getitem__(key Object) (Object, error) { func (d StringDict) M__delitem__(key Object) (Object, error) { str, ok := key.(String) - if ok { - _, ok := d[string(str)] - if ok { - delete(d, string(str)) - return None, nil - } + if !ok { + return nil, ExceptionNewf(KeyError, "%v", key) } - return nil, ExceptionNewf(KeyError, "%v", key) + _, ok = d[string(str)] + if !ok { + return nil, ExceptionNewf(KeyError, "%v", key) + } + delete(d, string(str)) + return None, nil } func (d StringDict) M__setitem__(key, value Object) (Object, error) { diff --git a/py/tests/dict.py b/py/tests/dict.py index a62a49ed..8fc9619e 100644 --- a/py/tests/dict.py +++ b/py/tests/dict.py @@ -49,6 +49,10 @@ doc="del" a = {'hello': 'world', 'hi': 'there'} del a["hello"] +def doDel(d, key): + del d[key] +assertRaises(KeyError, lambda: doDel(a, "bob")) +assertRaises(KeyError, lambda: doDel(a, 123)) assert not a.__contains__('hello') assert a.__contains__('hi')