gp

package module
v0.1.0 Latest Latest
Warning

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

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

README

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

Build Status Coverage Status 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

  • Python virtual environment.
  • Preprocess reference counting.
  • True multi-threading.
  • Support LLGo.

Examples

See the examples.

Hello World: Plot a line
package main

import . "github.com/cpunion/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/cpunion/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/cpunion/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/cpunion/go-python"
	"github.com/cpunion/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 (
	"os"

	. "github.com/cpunion/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 {
		// avoid gradio start subprocesses
		return
	}

	Initialize()
	defer Finalize()
	gr = ImportModule("gradio")
	fn := CreateFunc("update_examples", UpdateExamples,
		"(country, /)\n--\n\nUpdate examples based on country")
	// Would be (in the future):
	// fn := FuncOf(UpdateExamples)
	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", fn, dropdown, dataset)
	})
	demo.Call("launch")
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AllocCStr

func AllocCStr(s string) *C.char

func AllocCStrDontFree

func AllocCStrDontFree(s string) *C.char

func Cast

func Cast[U, T Objecter](obj T) (u U)

llgo:link Cast llgo.staticCast

func FetchError

func FetchError() error

FetchError returns the current Python error as a Go error

func Finalize

func Finalize()

func GoString

func GoString(s *C.char) string

func GoStringN

func GoStringN(s *C.char, n int) string

func Initialize

func Initialize()

func RunString

func RunString(code string) error

RunString executes Python code string and returns error if any

func SetError

func SetError(err error)

func SetTypeError

func SetTypeError(err error)

func ToValue

func ToValue(obj Object, v 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 (obj Bool) Ensure()

func (Bool) Nil

func (obj Bool) Nil() bool

func (Bool) Not

func (b Bool) Not() Bool

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 (obj Bytes) Ensure()

func (Bytes) Nil

func (obj Bytes) Nil() bool

type Char

type Char = C.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 (obj Complex) Ensure()

func (Complex) Imag

func (c Complex) Imag() float64

func (Complex) Nil

func (obj Complex) Nil() bool

func (Complex) Real

func (c Complex) Real() float64

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 (obj 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(fn func(key, value Object) bool)

func (Dict) Nil

func (obj Dict) Nil() bool

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 (obj 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 (obj Float) Nil() bool

type Func

type Func struct {
	Object
}

func CreateFunc

func CreateFunc(name string, fn any, doc string) 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) Nil

func (obj Func) Nil() bool

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 Int

type Int = C.int

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 (obj List) Ensure()

func (List) GetItem

func (l List) GetItem(index int) Object

func (List) Len

func (l List) Len() int

func (List) Nil

func (obj List) Nil() bool

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 (obj 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 (obj Long) Nil() bool

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 (obj Module) Ensure()

func (Module) Nil

func (obj Module) Nil() bool

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(v any) Object

func FromPy

func FromPy(obj *PyObject) Object

func Nil

func Nil() Object

func None

func None() Object

func (Object) AsBool

func (obj Object) AsBool() Bool

func (Object) AsBytes

func (obj Object) AsBytes() Bytes

func (Object) AsComplex

func (obj Object) AsComplex() Complex

func (Object) AsDict

func (obj Object) AsDict() Dict

func (Object) AsFloat

func (obj Object) AsFloat() Float

func (Object) AsFunc

func (obj Object) AsFunc() Func

func (Object) AsList

func (obj Object) AsList() List

func (Object) AsLong

func (obj Object) AsLong() Long

func (Object) AsModule

func (obj Object) AsModule() Module

func (Object) AsStr

func (obj Object) AsStr() Str

func (Object) AsTuple

func (obj Object) AsTuple() Tuple

func (Object) Attr

func (obj Object) Attr(name string) Object

func (Object) AttrBool

func (obj Object) AttrBool(name string) Bool

func (Object) AttrBytes

func (obj Object) AttrBytes(name string) Bytes

func (Object) AttrDict

func (obj Object) AttrDict(name string) Dict

func (Object) AttrFloat

func (obj Object) AttrFloat(name string) Float

func (Object) AttrFunc

func (obj Object) AttrFunc(name string) Func

func (Object) AttrList

func (obj Object) AttrList(name string) List

func (Object) AttrLong

func (obj Object) AttrLong(name string) Long

func (Object) AttrString

func (obj Object) AttrString(name string) Str

func (Object) AttrTuple

func (obj Object) AttrTuple(name string) Tuple

func (Object) Call

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

func (Object) Dir

func (obj Object) Dir() List

func (Object) Ensure

func (obj Object) Ensure()

func (Object) Equals

func (obj Object) Equals(other Objecter) bool

func (Object) IsBool

func (obj Object) IsBool() bool

func (Object) IsBytes

func (obj Object) IsBytes() bool

func (Object) IsComplex

func (obj Object) IsComplex() bool

func (Object) IsDict

func (obj Object) IsDict() bool

func (Object) IsFloat

func (obj Object) IsFloat() bool

func (Object) IsList

func (obj Object) IsList() bool

func (Object) IsLong

func (obj Object) IsLong() bool

func (Object) IsStr

func (obj Object) IsStr() bool

func (Object) IsTuple

func (obj Object) IsTuple() bool

func (Object) Nil

func (obj Object) Nil() bool

func (Object) Obj

func (obj Object) Obj() *PyObject

func (Object) Repr

func (obj Object) Repr() string

func (Object) SetAttr

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

func (Object) String

func (obj Object) String() string

func (Object) Type

func (obj Object) Type() Object

type Objecter

type Objecter interface {
	Obj() *PyObject

	Ensure()
	// contains filtered or unexported methods
}

type Pointer

type Pointer = unsafe.Pointer

type PyCFunction

type PyCFunction = C.PyCFunction

type PyObject

type PyObject = C.PyObject

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 (obj Str) Ensure()

func (Str) Len

func (s Str) Len() int

func (Str) Nil

func (obj Str) Nil() bool

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 (obj Tuple) Ensure()

func (Tuple) Get

func (t Tuple) Get(index int) Object

func (Tuple) Len

func (t Tuple) Len() int

func (Tuple) Nil

func (obj Tuple) Nil() bool

func (Tuple) ParseArgs

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

func (Tuple) Set

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

func (Tuple) Slice

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

type WChar

type WChar = C.wchar_t

Directories

Path Synopsis
demo
autoderef command
gradio command
module command
plot command
plot2 command

Jump to

Keyboard shortcuts

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