Skip to content

Commit 89966c1

Browse files
committed
Implement __getitem__ & __setitem__ for List and __getitem__ for Tuple
1 parent 9e25827 commit 89966c1

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

py/internal.go

+15
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,21 @@ func IndexInt(a Object) int {
6767
return intI
6868
}
6969

70+
// As IndexInt but if index is -ve addresses it from the end
71+
//
72+
// If index is out of range throws IndexError
73+
func IndexIntCheck(a Object, max int) int {
74+
i := IndexInt(a)
75+
if i < 0 {
76+
i += max
77+
}
78+
if i < 0 || i >= max {
79+
// FIXME IndexError
80+
panic("IndexError: list index out of range")
81+
}
82+
return i
83+
}
84+
7085
// Return the result of not a
7186
func Not(a Object) Object {
7287
switch MakeBool(a) {

py/list.go

+13
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,22 @@ func (t List) M__iter__() Object {
3535
return NewIterator(t)
3636
}
3737

38+
func (t List) M__getitem__(key Object) Object {
39+
i := IndexIntCheck(key, len(t))
40+
return t[i]
41+
}
42+
43+
func (t List) M__setitem__(key, value Object) Object {
44+
i := IndexIntCheck(key, len(t))
45+
t[i] = value
46+
return None
47+
}
48+
3849
// Check interface is satisfied
3950
var _ I__len__ = List(nil)
4051
var _ I__bool__ = List(nil)
4152
var _ I__iter__ = List(nil)
53+
var _ I__getitem__ = List(nil)
54+
var _ I__setitem__ = List(nil)
4255

4356
// var _ richComparison = List(nil)

py/tuple.go

+6
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,15 @@ func (t Tuple) M__iter__() Object {
3434
return NewIterator(t)
3535
}
3636

37+
func (t Tuple) M__getitem__(key Object) Object {
38+
i := IndexIntCheck(key, len(t))
39+
return t[i]
40+
}
41+
3742
// Check interface is satisfied
3843
var _ I__len__ = Tuple(nil)
3944
var _ I__bool__ = Tuple(nil)
4045
var _ I__iter__ = Tuple(nil)
46+
var _ I__getitem__ = Tuple(nil)
4147

4248
// var _ richComparison = Tuple(nil)

0 commit comments

Comments
 (0)