gp

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 22, 2024 License: MIT Imports: 9 Imported by: 0

README

go-python: Write Python in Go - The most intuitive Python wrapper for Golang

Build Status codecov GitHub go.mod Go version GitHub commits GitHub release Go Report Card Go Reference

Goal

  • Automatically DecRef for Python objects.
  • Typed Python objects.
  • Most intuitive and easy to use.

Features

  • Call Python in Go.
    • Basic types.
      • Integers.
      • Floats.
      • Strings.
      • Bytes.
      • Booleans.
      • Lists.
      • Tuples.
      • Dicts.
    • Modules.
    • Functions
      • Keyword arguments.
      • Mapping arguments and return values.
      • Default arguments.
  • Call Go in Python.
    • Export Go functions, struct types to Python.
    • Auto export field types if it's a struct.
    • Auto generate function signatures (used by gradio).
  • Basic tests on common used libraries.
    • matplotlib
    • gradio

Plans

Examples

See the examples.

Hello World: Plot a line
package main

import . "github.com/gotray/go-python"

func main() {
	Initialize()
	plt := ImportModule("matplotlib.pyplot")
	plt.Call("plot", MakeTuple(5, 10), MakeTuple(10, 15), KwArgs{"color": "red"})
	plt.Call("show")
}

Typed Python Objects
package main

import . "github.com/gotray/go-python"

type plt struct {
	Module
}

func Plt() plt {
	return plt{ImportModule("matplotlib.pyplot")}
}

func (m plt) Plot(args ...any) Object {
	return m.Call("plot", args...)
}

func (m plt) Show() {
	m.Call("show")
}

func main() {
	Initialize()
	defer Finalize()
	plt := Plt()
	plt.Plot([]int{5, 10}, []int{10, 15}, KwArgs{"color": "red"})
	plt.Show()
}

Define Python Objects with Go
package foo

import (
	"fmt"

	. "github.com/gotray/go-python"
)

type Point struct {
	X float64
	Y float64
}

func (p *Point) init(x, y float64) {
	p.X = x
	p.Y = y
}

func (p *Point) Print() {
	fmt.Printf("Point(%f, %f)\n", p.X, p.Y)
}

func (p *Point) Distance() float64 {
	return p.X * p.Y
}

// Move method for Point
func (p *Point) Move(dx, dy float64) {
	p.X += dx
	p.Y += dy
}

func Add(a, b int) int {
	return a + b
}

func InitFooModule() Module {
	m := CreateModule("foo")
	// Add the function to the module
	m.AddMethod("add", Add, "(a, b) -> float\n--\n\nAdd two integers.")
	// Add the type to the module
	m.AddType(Point{}, (*Point).init, "Point", "Point objects")
	return m
}

Call foo module from Python and Go.

package main

import (
	"fmt"

	. "github.com/gotray/go-python"
	"github.com/gotray/go-python/demo/module/foo"
)

func main() {
	Initialize()
	defer Finalize()
	fooMod := foo.InitFooModule()
	GetModuleDict().SetString("foo", fooMod)

	Main1(fooMod)
	Main2()
}

func Main1(fooMod Module) {
	sum := fooMod.Call("add", 1, 2).AsLong()
	fmt.Printf("Sum of 1 + 2: %d\n", sum.Int64())

	dict := fooMod.Dict()
	Point := dict.Get(MakeStr("Point")).AsFunc()

	point := Point.Call(3, 4)
	fmt.Printf("dir(point): %v\n", point.Dir())
	fmt.Printf("x: %v, y: %v\n", point.Attr("x"), point.Attr("y"))

	distance := point.Call("distance").AsFloat()
	fmt.Printf("Distance of 3 * 4: %f\n", distance.Float64())

	point.Call("move", 1, 2)
	fmt.Printf("x: %v, y: %v\n", point.Attr("x"), point.Attr("y"))

	distance = point.Call("distance").AsFloat()
	fmt.Printf("Distance of 4 * 6: %f\n", distance.Float64())

	point.Call("print")
}

func Main2() {
	fmt.Printf("=========== Main2 ==========\n")
	_ = RunString(`
import foo
point = foo.Point(3, 4)
print("dir(point):", dir(point))
print("x:", point.x)
print("y:", point.y)

print("distance:", point.distance())

point.move(1, 2)
print("x:", point.x)
print("y:", point.y)
print("distance:", point.distance())

point.print()
	`)
}

Call gradio
package main

import (
	"fmt"
	"os"

	. "github.com/gotray/go-python"
)

/*
import gradio as gr

def update_examples(country):
		print("country:", country)
    if country == "USA":
        return gr.Dataset(samples=[["Chicago"], ["Little Rock"], ["San Francisco"]])
    else:
        return gr.Dataset(samples=[["Islamabad"], ["Karachi"], ["Lahore"]])

with gr.Blocks() as demo:
    dropdown = gr.Dropdown(label="Country", choices=["USA", "Pakistan"], value="USA")
    textbox = gr.Textbox()
    examples = gr.Examples([["Chicago"], ["Little Rock"], ["San Francisco"]], textbox)
    dropdown.change(update_examples, dropdown, examples.dataset)

demo.launch()
*/

var gr Module

func updateExamples(country string) Object {
	println("country:", country)
	if country == "USA" {
		return gr.Call("Dataset", KwArgs{
			"samples": [][]string{{"Chicago"}, {"Little Rock"}, {"San Francisco"}},
		})
	} else {
		return gr.Call("Dataset", KwArgs{
			"samples": [][]string{{"Islamabad"}, {"Karachi"}, {"Lahore"}},
		})
	}
}

func main() {
	if len(os.Args) > 2 {
		// start subprocesses
		fmt.Println("start subprocess:", os.Args)
		os.Exit(RunMain(os.Args))
	}

	Initialize()
	defer Finalize()
	gr = ImportModule("gradio")
	demo := With(gr.Call("Blocks"), func(v Object) {
		dropdown := gr.Call("Dropdown", KwArgs{
			"label":   "Country",
			"choices": []string{"USA", "Pakistan"},
			"value":   "USA",
		})
		textbox := gr.Call("Textbox")
		examples := gr.Call("Examples", [][]string{{"Chicago"}, {"Little Rock"}, {"San Francisco"}}, textbox)
		dataset := examples.Attr("dataset")
		dropdown.Call("change", updateExamples, dropdown, dataset)
	})
	demo.Call("launch")
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FetchError

func FetchError() error

FetchError returns the current Python error as a Go error

func Finalize

func Finalize()

func GoString

func GoString(s *Char) string

func GoStringN

func GoStringN(s *Char, n int) string

func Initialize

func Initialize()

func RunMain

func RunMain(args []string) int

func RunString

func RunString(code string) error

RunString executes Python code string and returns error if any

func SetTypeError

func SetTypeError(err error)

func ToValue

func ToValue(from Object, to reflect.Value) bool

func With

func With[T Objecter](obj T, fn func(v T)) T

Types

type Bool

type Bool struct {
	Object
}

func False

func False() Bool

func MakeBool

func MakeBool(b bool) Bool

func True

func True() Bool

func (Bool) Bool

func (b Bool) Bool() bool

func (Bool) Ensure

func (o Bool) Ensure()

func (Bool) Nil

func (o Bool) Nil() bool

func (Bool) Not

func (b Bool) Not() Bool

func (Bool) RefCount

func (o Bool) RefCount() int

type Bytes

type Bytes struct {
	Object
}

func BytesFromStr

func BytesFromStr(s string) Bytes

func MakeBytes

func MakeBytes(bytes []byte) Bytes

func (Bytes) Bytes

func (b Bytes) Bytes() []byte

func (Bytes) Decode

func (b Bytes) Decode(encoding string) Str

func (Bytes) Ensure

func (o Bytes) Ensure()

func (Bytes) Nil

func (o Bytes) Nil() bool

func (Bytes) RefCount

func (o Bytes) RefCount() int

type Char

type Char = C.char

func AllocCStr

func AllocCStr(s string) *Char

func AllocCStrDontFree

func AllocCStrDontFree(s string) *Char

type Complex

type Complex struct {
	Object
}

func MakeComplex

func MakeComplex(f complex128) Complex

func (Complex) Complex128

func (c Complex) Complex128() complex128

func (Complex) Ensure

func (o Complex) Ensure()

func (Complex) Imag

func (c Complex) Imag() float64

func (Complex) Nil

func (o Complex) Nil() bool

func (Complex) Real

func (c Complex) Real() float64

func (Complex) RefCount

func (o Complex) RefCount() int

type Dict

type Dict struct {
	Object
}

func DictFromPairs

func DictFromPairs(pairs ...any) Dict

func GetModuleDict

func GetModuleDict() Dict

func MakeDict

func MakeDict(m map[any]any) Dict

func (Dict) Del

func (d Dict) Del(key Objecter)

func (Dict) Ensure

func (o Dict) Ensure()

func (Dict) Get

func (d Dict) Get(key Objecter) Object

func (Dict) GetString

func (d Dict) GetString(key string) Object

func (Dict) HasKey

func (d Dict) HasKey(key any) bool

func (Dict) Items

func (d Dict) Items() func(func(Object, Object) bool)

func (Dict) Nil

func (o Dict) Nil() bool

func (Dict) RefCount

func (o Dict) RefCount() int

func (Dict) Set

func (d Dict) Set(key, value Objecter)

func (Dict) SetString

func (d Dict) SetString(key string, value Objecter)

type Float

type Float struct {
	Object
}

Float represents a Python float object. It provides methods to convert between Go float types and Python float objects, as well as checking numeric properties.

func MakeFloat

func MakeFloat(f float64) Float

func (Float) Ensure

func (o Float) Ensure()

func (Float) Float32

func (f Float) Float32() float32

func (Float) Float64

func (f Float) Float64() float64

func (Float) IsInteger

func (f Float) IsInteger() Bool

func (Float) Nil

func (o Float) Nil() bool

func (Float) RefCount

func (o Float) RefCount() int

type Func

type Func struct {
	Object
}

func CreateFunc

func CreateFunc(name string, fn any, doc string) Func

func FuncOf

func FuncOf(fn any) Func

func (Func) Call

func (f Func) Call(args ...any) Object

func (Func) CallObject

func (f Func) CallObject(args Tuple) Object

func (Func) CallObjectKw

func (f Func) CallObjectKw(args Tuple, kw KwArgs) Object

func (Func) Ensure

func (f Func) Ensure()

func (Func) Name

func (f Func) Name() string

func (Func) Nil

func (o Func) Nil() bool

func (Func) RefCount

func (o Func) RefCount() int

type InputType

type InputType = C.int
const (
	SingleInput InputType = C.Py_single_input
	FileInput   InputType = C.Py_file_input
	EvalInput   InputType = C.Py_eval_input
)

type KwArgs

type KwArgs map[string]any

type List

type List struct {
	Object
}

func MakeList

func MakeList(args ...any) List

func (List) Append

func (l List) Append(obj Objecter)

func (List) Ensure

func (o List) Ensure()

func (List) GetItem

func (l List) GetItem(index int) Object

func (List) Len

func (l List) Len() int

func (List) Nil

func (o List) Nil() bool

func (List) RefCount

func (o List) RefCount() int

func (List) SetItem

func (l List) SetItem(index int, item Objecter)

type Long

type Long struct {
	Object
}

func LongFromFloat64

func LongFromFloat64(v float64) Long

func LongFromString

func LongFromString(s string, base int) Long

func LongFromUintptr

func LongFromUintptr(v uintptr) Long

func LongFromUnicode

func LongFromUnicode(u Object, base int) Long

func MakeLong

func MakeLong(i int64) Long

func (Long) Ensure

func (o Long) Ensure()

func (Long) Float64

func (l Long) Float64() float64

func (Long) Int

func (l Long) Int() int

func (Long) Int64

func (l Long) Int64() int64

func (Long) Nil

func (o Long) Nil() bool

func (Long) RefCount

func (o Long) RefCount() int

func (Long) Uint

func (l Long) Uint() uint

func (Long) Uint64

func (l Long) Uint64() uint64

func (Long) Uintptr

func (l Long) Uintptr() uintptr

type Module

type Module struct {
	Object
}

func CreateModule

func CreateModule(name string) Module

func GetModule

func GetModule(name string) Module

func ImportModule

func ImportModule(name string) Module

func MainModule

func MainModule() Module

func (Module) AddMethod

func (m Module) AddMethod(name string, fn any, doc string) Func

func (Module) AddObject

func (m Module) AddObject(name string, obj Object) int

func (Module) AddType

func (m Module) AddType(obj, init any, name, doc string) Object

func (Module) Dict

func (m Module) Dict() Dict

func (Module) Ensure

func (o Module) Ensure()

func (Module) Name

func (m Module) Name() string

func (Module) Nil

func (o Module) Nil() bool

func (Module) RefCount

func (o Module) RefCount() int

type Object

type Object struct {
	// contains filtered or unexported fields
}

func CompileString

func CompileString(code, filename string, start InputType) (Object, error)

func EvalCode

func EvalCode(code Object, globals, locals Dict) Object

func From

func From(from any) Object

func FromPy

func FromPy(obj *cPyObject) Object

func Nil

func Nil() Object

func None

func None() Object

func (Object) AsBool

func (o Object) AsBool() Bool

func (Object) AsBytes

func (o Object) AsBytes() Bytes

func (Object) AsComplex

func (o Object) AsComplex() Complex

func (Object) AsDict

func (o Object) AsDict() Dict

func (Object) AsFloat

func (o Object) AsFloat() Float

func (Object) AsFunc

func (o Object) AsFunc() Func

func (Object) AsList

func (o Object) AsList() List

func (Object) AsLong

func (o Object) AsLong() Long

func (Object) AsModule

func (o Object) AsModule() Module

func (Object) AsStr

func (o Object) AsStr() Str

func (Object) AsTuple

func (o Object) AsTuple() Tuple

func (Object) Attr

func (o Object) Attr(name string) Object

func (Object) AttrBool

func (o Object) AttrBool(name string) Bool

func (Object) AttrBytes

func (o Object) AttrBytes(name string) Bytes

func (Object) AttrDict

func (o Object) AttrDict(name string) Dict

func (Object) AttrFloat

func (o Object) AttrFloat(name string) Float

func (Object) AttrFunc

func (o Object) AttrFunc(name string) Func

func (Object) AttrList

func (o Object) AttrList(name string) List

func (Object) AttrLong

func (o Object) AttrLong(name string) Long

func (Object) AttrString

func (o Object) AttrString(name string) Str

func (Object) AttrTuple

func (o Object) AttrTuple(name string) Tuple

func (Object) Call

func (o Object) Call(name string, args ...any) Object

func (Object) Dir

func (o Object) Dir() List

func (Object) Ensure

func (o Object) Ensure()

func (Object) Equals

func (o Object) Equals(other Objecter) bool

func (Object) IsBool

func (o Object) IsBool() bool

func (Object) IsBytes

func (o Object) IsBytes() bool

func (Object) IsComplex

func (o Object) IsComplex() bool

func (Object) IsDict

func (o Object) IsDict() bool

func (Object) IsFloat

func (o Object) IsFloat() bool

func (Object) IsFunc

func (o Object) IsFunc() bool

func (Object) IsList

func (o Object) IsList() bool

func (Object) IsLong

func (o Object) IsLong() bool

func (Object) IsStr

func (o Object) IsStr() bool

func (Object) IsTuple

func (o Object) IsTuple() bool

func (Object) Nil

func (o Object) Nil() bool

func (Object) RefCount

func (o Object) RefCount() int

func (Object) Repr

func (o Object) Repr() string

func (Object) SetAttr

func (o Object) SetAttr(name string, value any)

func (Object) String

func (o Object) String() string

func (Object) Type

func (o Object) Type() Object

type Objecter

type Objecter interface {
	Ensure()
	// contains filtered or unexported methods
}

type Str

type Str struct {
	Object
}

func MakeStr

func MakeStr(s string) Str

func (Str) ByteLen

func (s Str) ByteLen() int

func (Str) Encode

func (s Str) Encode(encoding string) Bytes

func (Str) Ensure

func (o Str) Ensure()

func (Str) Len

func (s Str) Len() int

func (Str) Nil

func (o Str) Nil() bool

func (Str) RefCount

func (o Str) RefCount() int

func (Str) String

func (s Str) String() string

type Tuple

type Tuple struct {
	Object
}

func MakeTuple

func MakeTuple(args ...any) Tuple

func MakeTupleWithLen

func MakeTupleWithLen(len int) Tuple

func (Tuple) Ensure

func (o Tuple) Ensure()

func (Tuple) Get

func (t Tuple) Get(index int) Object

func (Tuple) Len

func (t Tuple) Len() int

func (Tuple) Nil

func (o Tuple) Nil() bool

func (Tuple) ParseArgs

func (t Tuple) ParseArgs(addrs ...any) bool

func (Tuple) RefCount

func (o Tuple) RefCount() int

func (Tuple) Set

func (t Tuple) Set(index int, obj Objecter)

func (Tuple) Slice

func (t Tuple) Slice(low, high int) Tuple

Directories

Path Synopsis
demo

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL