99
1010package py
1111
12- import "bytes"
12+ import (
13+ "bytes"
14+ )
1315
1416const dictDoc = `dict() -> new empty dictionary
1517dict(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
2426var (
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
98100type 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
101134func (o StringDict ) Type () * Type {
102135 return StringDictType
0 commit comments