Skip to content

Commit 337df2a

Browse files
authored
py: improve dict intialization method
1 parent 5ef0384 commit 337df2a

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

py/dict.go

+35-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@
99

1010
package py
1111

12-
import "bytes"
12+
import (
13+
"bytes"
14+
)
1315

1416
const dictDoc = `dict() -> new empty dictionary
1517
dict(mapping) -> new dictionary initialized from a mapping object's
@@ -22,7 +24,7 @@ dict(**kwargs) -> new dictionary initialized with the name=value pairs
2224
in the keyword argument list. For example: dict(one=1, two=2)`
2325

2426
var (
25-
StringDictType = NewType("dict", dictDoc)
27+
StringDictType = NewTypeX("dict", dictDoc, DictNew, nil)
2628
DictType = NewType("dict", dictDoc)
2729
expectingDict = ExceptionNewf(TypeError, "a dict is required")
2830
)
@@ -97,6 +99,37 @@ func init() {
9799
// Used for variables etc where the keys can only be strings
98100
type StringDict map[string]Object
99101

102+
// DictNew
103+
func DictNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error) {
104+
if len(args) > 1 {
105+
return nil, ExceptionNewf(TypeError, "dict expects at most one argument")
106+
}
107+
out := NewStringDict()
108+
if len(args) == 1 {
109+
arg := args[0]
110+
seq, err := SequenceList(arg)
111+
if err != nil {
112+
return nil, err
113+
}
114+
for _, i := range seq.Items {
115+
switch z := i.(type) {
116+
case Tuple:
117+
if zStr, ok := z[0].(String); ok {
118+
out[string(zStr)] = z[1]
119+
}
120+
default:
121+
return nil, ExceptionNewf(TypeError, "non-tuple sequence")
122+
}
123+
}
124+
}
125+
if len(kwargs) > 0 {
126+
for k, v := range kwargs {
127+
out[k] = v
128+
}
129+
}
130+
return out, nil
131+
}
132+
100133
// Type of this StringDict object
101134
func (o StringDict) Type() *Type {
102135
return StringDictType

py/tests/dict.py

+15
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,21 @@ def doDel(d, key):
5656
assert not a.__contains__('hello')
5757
assert a.__contains__('hi')
5858

59+
doc="init"
60+
a = dict( zip( "a,b,c".split(","), "1,2,3".split(",") ) )
61+
assert a["a"] == "1"
62+
assert a["b"] == "2"
63+
assert a["c"] == "3"
64+
65+
a = dict(a="1", b="2", c="3")
66+
assert a["a"] == "1"
67+
assert a["b"] == "2"
68+
assert a["c"] == "3"
69+
70+
assertRaises(TypeError, dict, "a")
71+
assertRaises(TypeError, dict, 1)
72+
assertRaises(TypeError, dict, {"a":1}, {"b":2})
73+
5974
doc="__contain__"
6075
a = {'hello': 'world'}
6176
assert a.__contains__('hello')

0 commit comments

Comments
 (0)