janpfeifer / gonb

GoNB, a Go Notebook Kernel for Jupyter
https://github.com/janpfeifer/gonb
MIT License
467 stars 32 forks source link

Is there plan to implement some hack print like gruns/icecream #98

Closed potoo0 closed 3 months ago

potoo0 commented 3 months ago

icecream#inspect-variables

expected:

func genInt() int {
  return 1
}
s := "hello"

dev.Print(s, genInt()) // s: hello, genInt(): 1
janpfeifer commented 3 months ago

hi @potoo0 ,

I didn't know about icecream, thanks for bringing it up -- it seems a very useful tool.

But it seems to work well (mostly) in gonb, check out:

image

(Notice the bug with Ic() with no parameters, but I suspect that doesn't matter much ?)

Were you looking for something else ?

cheers

potoo0 commented 3 months ago

Sorry, I didn't do enough digging. My first idea was to use ast to rewrite dev.Print(...) as fmt.Printf(<pattern>, ...), after the cell code is written to the file.

I also implemented a simple version, but it seems unnecessary after this.

selX.Name = "fmt"
sel.Sel.Name = "Printf"
label := identLabel(fset, expr)
expr.Args = append([]ast.Expr{&ast.BasicLit{Kind: token.STRING, Value: label}}, expr.Args...)
// ...
// format.Node overwrite main.go

// identLabel ...
for idx, arg := range expr.Args {
  builder.WriteString(AnsiCyan)
  err := printer.Fprint(&builder, fset, arg)
  if err != nil {
    builder.WriteString("-")
  }
  builder.WriteString(AnsiReset)
  builder.WriteString(": %+v")
  if idx+1 != argLen {
    builder.WriteString(", ")
  }
}

image