gpython icon indicating copy to clipboard operation
gpython copied to clipboard

Implement dict to receive Object as key, not only String

Open HyeockJinKim opened this issue 6 years ago • 10 comments

https://github.com/go-python/gpython/blob/33327c5231b03c84972bec57262694aebbaa1e84/py/dict.go#L68

Change the dict to receive a hashable object as a key, not just a string. I will change it so that the object can be looked up through the hash value of the object.

Store the object in the slice and use the map to find the index of the stored object through the hash value.

make([]Object, 0, len(default_size))  // slice to store object  (index -> Object)
type Dict map[HashIndex]int // map to store index of slice  (Hash -> index)

Is it ok to implement dict this way?

HyeockJinKim avatar Oct 14 '19 03:10 HyeockJinKim

@HyeockJinKim I 'd like to recommend to implement dict by wrapping the map throw using the delegate pattern.

type Dict struct {
...
}

func (d *Dict) Put(...) (Object, error) {
...
}

func (d *Dict) Get(...) (Object, error) {
...
}

cc @ncw

corona10 avatar Oct 14 '19 09:10 corona10

cc @sbinet

corona10 avatar Oct 14 '19 09:10 corona10

if I am not mistaken, CPython dicts are not ordered (there's collections.OrderedDict for that.)

so, couldn't we just use map[Object]Object at the core of this data structure?

sbinet avatar Oct 14 '19 09:10 sbinet

@sbinet FYI

Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.

He might want to implement this feature. It is okay that we decide to broken 3.4 compatibilities. (https://github.com/go-python/gpython/pull/74#issuecomment-531559220)

corona10 avatar Oct 14 '19 10:10 corona10

@HyeockJinKim However, as @sbinet commented. I'd like to recommend you implement unordered key dictionary as the 1st milestone. That will be enough for the 1st step.

cc @ncw @sbinet

corona10 avatar Oct 14 '19 10:10 corona10

I stand corrected :)

ok, then what about:

type Dict struct {
    keys map[Object]int // key to index into slice of vals
    vals []Object       // values associated with the above keys
}

(I think we can rely on Go's map hashing mechanism)

sbinet avatar Oct 14 '19 10:10 sbinet

and if we want to retain insertion order:

type Dict struct {
    keys  map[Object]int
    items [][2]Object // key-value pair
}

sbinet avatar Oct 14 '19 10:10 sbinet

Does anyone have a fork for this issue? Would be willing to give it a shot.

ashermancinelli avatar Oct 19 '19 02:10 ashermancinelli

@ashermancinelli please ping to @HyeockJinKim He might work on this issue :)

corona10 avatar Oct 19 '19 07:10 corona10

I'm working on this issue right now. I will work quickly and PR.

HyeockJinKim avatar Oct 19 '19 08:10 HyeockJinKim