Skip to content

Adding the 'add' method to the set class #212

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 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
11 changes: 11 additions & 0 deletions py/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,17 @@ func NewSetFromItems(items []Object) *Set {
return s
}

func init() {
SetType.Dict["add"] = MustNewMethod("add", func(self Object, args Tuple) (Object, error) {
setSelf := self.(*Set)
if len(args) != 1 {
return nil, ExceptionNewf(TypeError, "append() takes exactly one argument (%d given)", len(args))
}
setSelf.Add(args[0])
return NoneType{}, nil
}, 0, "add(value)")
}

// Add an item to the set
func (s *Set) Add(item Object) {
s.items[item] = SetValue{}
Expand Down
14 changes: 14 additions & 0 deletions py/tests/set.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

from libtest import assertRaises

doc="__and__"
a = {1, 2, 3}
b = {2, 3, 4, 5}
Expand Down Expand Up @@ -81,6 +83,18 @@
assert 4 in c
assert 5 in c

doc="add"
a = set()
a.add(1)
a.add(2)
a.add(3)
assert len(a) == 3
assert 1 in a
assert 2 in a
assert 3 in a
assert 4 not in a
assertRaises(TypeError, lambda: a.add())

doc="__eq__, __ne__"
a = set([1,2,3])
assert a.__eq__(3) != True
Expand Down