py2many icon indicating copy to clipboard operation
py2many copied to clipboard

python tuple in golang

Open QGB opened this issue 4 years ago • 2 comments

t.py

params = (
    ('start', '2021-05-20T23:59:59.000Z'),
    ('end', '2021-06-04T23:59:59.001Z'),
    ('groupName', 'web'),
)
print(params)

converting...

/root/anaconda3/bin/py2many --go=1 --outdir ./ ./t.py
Writing to: .
t.py...t.go
t.go:9:1: expected declaration, found fmt
Error: ['gofmt', '-w', 't.go'] (code: 2):
NoneNone

the result t.go

package main

import (
"fmt")



var params = "start", "2021-05-20T23:59:59.000Z", "end", "2021-06-04T23:59:59.001Z", "groupName", "web"
fmt.Printf("%v\n",params);

try

go build t.go
# command-line-arguments
./t.go:8:5: assignment mismatch: 1 variables but 6 values
./t.go:9:1: syntax error: non-declaration statement outside function body

QGB avatar Jun 17 '21 13:06 QGB

I get that the current code doesn't compile. Given that Go doesn't have tuples (https://github.com/golang/go/issues/32941), what do you want the generated code to do?

a, b, c, d, e, f = 'start', '2021-05-20T23:59:59.000Z', 'end', '2021-06-04T23:59:59.001Z', 'groupName', 'web'

if __name__ == '__main__':
    print(a, b, c, d, e, f)

transpiles ok. If you want the generated to code to define types, it's possible to recognize this pattern and write a Go specific rewriter (GoMethodCallRewriter is an example rewriter).

A workaround is to use:

@dataclass
class Pair:
  first: str
  second: str

adsharma avatar Jun 17 '21 18:06 adsharma

https://stackoverflow.com/questions/13670818/pair-tuple-data-type-in-go provides a few mechanisms. https://github.com/barweiss/go-tuple by @barweiss looks ideal for our purposes, however it will require that we only support go 1.18+

jayvdb avatar Jun 19 '22 13:06 jayvdb