Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updating dict intialization method #217

Merged
merged 2 commits into from
Jan 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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")
sbinet marked this conversation as resolved.
Show resolved Hide resolved
}
out := NewStringDict()
if len(args) == 1 {
arg := args[0]
seq, err := SequenceList(arg)
if err != nil {
return nil, err
sbinet marked this conversation as resolved.
Show resolved Hide resolved
}
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