go-python / gpython

gpython is a python interpreter written in go "batteries not included"
BSD 3-Clause "New" or "Revised" License
879 stars 94 forks source link

How would i go about writing a new module? #168

Closed glaukiol1 closed 2 years ago

glaukiol1 commented 2 years ago

Hi

I want to contribute to this project by writing a module; specifically the JSON module (the one that is in python's standard library). I have seen the source code and have an idea of how I should go about this. So my question is; do I create a folder and put the .go file in there? Something like json/json.go? Also any tips on writing modules would help, thanks!

drew-512 commented 2 years ago

Hi friend, have you looked at the 'Vacation' embedded module example? That should demonstrate all the things you're looking for. Feel free to ask specific questions here.

Drew

raff commented 2 years ago

The math package also implements Python "math". Look for the init method at the bottom, where it registers the module: https://github.com/go-python/gpython/blob/master/math/math.go#L1290

glaukiol1 commented 2 years ago

Im stuck on converting a Go map[string]interface{} to a py.StringDict. Any help?

glaukiol1 commented 2 years ago

@raff @drew-512

raff commented 2 years ago

StringDict is a map[string]Object so you need to convert the Go values to the corresponding objects. For most of them it's a simple cast, but you'll have to check the implementaiton:

func mapToDict(m map[string]interface{}) py.StringDict {
   pmap := py.StringDict{}

   for k, v := range m {
      switch v := v.(type) {
         case string:
            pmap[k] = String(v)

          case int:
             pmap[k] = Int(v)

          case bool:
            pmap[k] = Bool(v)

          ....
   }
}

If your map is the ouput of json.Decode / json.Unmarshal you may need to play with the numeric types (but it may be ok to always convert json numbers to py.Float - it depends how close you want to be to the python implementation.

One thing to consider is doing stream decoding (parse the file token by token). This should allow to also implement things like "object_pair_hooks" and JSONDecoder (and in any case it would save double-allocating memory.

ahdekkers commented 1 year ago

Was any progress made with this?

drew-512 commented 1 year ago

I'm happy to work with anyone is seriously interested in building. Happy to give a tour and walk through of the codebase. That said, the embedding example is relatively easy to grok. Anyone who reads the comments and follows the breadcrumbs will be ready to write a module. That example is specifically intended to onboard new folks.