9
9
10
10
package py
11
11
12
- import "bytes"
12
+ import (
13
+ "bytes"
14
+ )
13
15
14
16
const dictDoc = `dict() -> new empty dictionary
15
17
dict(mapping) -> new dictionary initialized from a mapping object's
@@ -22,7 +24,7 @@ dict(**kwargs) -> new dictionary initialized with the name=value pairs
22
24
in the keyword argument list. For example: dict(one=1, two=2)`
23
25
24
26
var (
25
- StringDictType = NewType ("dict" , dictDoc )
27
+ StringDictType = NewTypeX ("dict" , dictDoc , DictNew , nil )
26
28
DictType = NewType ("dict" , dictDoc )
27
29
expectingDict = ExceptionNewf (TypeError , "a dict is required" )
28
30
)
@@ -97,6 +99,37 @@ func init() {
97
99
// Used for variables etc where the keys can only be strings
98
100
type StringDict map [string ]Object
99
101
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
+
100
133
// Type of this StringDict object
101
134
func (o StringDict ) Type () * Type {
102
135
return StringDictType
0 commit comments