Skip to content

Adding __delitem__ to dict #215

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 14, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Adding __delitem__ to dict. Enables the 'del' command to delete items…
… from a dict
  • Loading branch information
kellrott committed Jan 12, 2023
commit 348f19b415ce14da9dc48ab6ab6c34071ae4f6f0
12 changes: 12 additions & 0 deletions py/dict.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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)
str, ok := key.(String)
if !ok {
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

yes, it's longer, but only in the vertical dimension (however, it's less indented)

}

func (d StringDict) M__setitem__(key, value Object) (Object, error) {
str, ok := key.(String)
if !ok {
Expand Down
6 changes: 6 additions & 0 deletions py/tests/dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

perhaps add a couple of cases that exercize the 2 ExceptionNewf branches ?

doc="__contain__"
a = {'hello': 'world'}
assert a.__contains__('hello')
Expand Down