Skip to content

Commit 8e99b32

Browse files
authored
py: add the 'add' method to the set class
1 parent 6f8e06a commit 8e99b32

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

py/set.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,17 @@ func NewSetFromItems(items []Object) *Set {
4646
return s
4747
}
4848

49+
func init() {
50+
SetType.Dict["add"] = MustNewMethod("add", func(self Object, args Tuple) (Object, error) {
51+
setSelf := self.(*Set)
52+
if len(args) != 1 {
53+
return nil, ExceptionNewf(TypeError, "append() takes exactly one argument (%d given)", len(args))
54+
}
55+
setSelf.Add(args[0])
56+
return NoneType{}, nil
57+
}, 0, "add(value)")
58+
}
59+
4960
// Add an item to the set
5061
func (s *Set) Add(item Object) {
5162
s.items[item] = SetValue{}

py/tests/set.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
# Use of this source code is governed by a BSD-style
33
# license that can be found in the LICENSE file.
44

5+
from libtest import assertRaises
6+
57
doc="__and__"
68
a = {1, 2, 3}
79
b = {2, 3, 4, 5}
@@ -81,6 +83,18 @@
8183
assert 4 in c
8284
assert 5 in c
8385

86+
doc="add"
87+
a = set()
88+
a.add(1)
89+
a.add(2)
90+
a.add(3)
91+
assert len(a) == 3
92+
assert 1 in a
93+
assert 2 in a
94+
assert 3 in a
95+
assert 4 not in a
96+
assertRaises(TypeError, lambda: a.add())
97+
8498
doc="__eq__, __ne__"
8599
a = set([1,2,3])
86100
assert a.__eq__(3) != True

0 commit comments

Comments
 (0)