Skip to content

Commit

Permalink
py: improve dict intialization method
Browse files Browse the repository at this point in the history
  • Loading branch information
kellrott authored Jan 18, 2023
1 parent 5ef0384 commit 337df2a
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
37 changes: 35 additions & 2 deletions py/dict.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@

package py

import "bytes"
import (
"bytes"
)

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

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

// DictNew
func DictNew(metatype *Type, args Tuple, kwargs StringDict) (Object, error) {
if len(args) > 1 {
return nil, ExceptionNewf(TypeError, "dict expects at most one argument")
}
out := NewStringDict()
if len(args) == 1 {
arg := args[0]
seq, err := SequenceList(arg)
if err != nil {
return nil, err
}
for _, i := range seq.Items {
switch z := i.(type) {
case Tuple:
if zStr, ok := z[0].(String); ok {
out[string(zStr)] = z[1]
}
default:
return nil, ExceptionNewf(TypeError, "non-tuple sequence")
}
}
}
if len(kwargs) > 0 {
for k, v := range kwargs {
out[k] = v
}
}
return out, nil
}

// Type of this StringDict object
func (o StringDict) Type() *Type {
return StringDictType
Expand Down
15 changes: 15 additions & 0 deletions py/tests/dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,21 @@ def doDel(d, key):
assert not a.__contains__('hello')
assert a.__contains__('hi')

doc="init"
a = dict( zip( "a,b,c".split(","), "1,2,3".split(",") ) )
assert a["a"] == "1"
assert a["b"] == "2"
assert a["c"] == "3"

a = dict(a="1", b="2", c="3")
assert a["a"] == "1"
assert a["b"] == "2"
assert a["c"] == "3"

assertRaises(TypeError, dict, "a")
assertRaises(TypeError, dict, 1)
assertRaises(TypeError, dict, {"a":1}, {"b":2})

doc="__contain__"
a = {'hello': 'world'}
assert a.__contains__('hello')
Expand Down

0 comments on commit 337df2a

Please sign in to comment.