A simple example

This is very simple example that just shows calling a function implemented in Go from Python.

Let's say the we have the following code in pymodule.go:

package simple

import (
	"fmt"
	"gopy"
)

func example(args *py.Tuple) (py.Object, error) {
	fmt.Printf("simple.example: %v\n", args)
	py.None.Incref()
	return py.None, nil
}

func init() {
	methods := []py.Method{
		{"example", example, "example function"},
	}

	_, err := py.InitModule("simple", methods)
	if err != nil {
		panic(err)
	}
}

We can compile this into a CPython extension module simple.so (the module name is the Go package name) with the following command:

> gopy pymodule.go

If we now run the following Python code:

import simple

simple.example("hello", {123: True})

Then we get the following output:

simple.example: [hello map[123:true]]

A parallel example

This is a slightly more complicated example, where we are doing some work in a background goroutine that is left running when the called function returns. In this example we simulate expensive computation, or similar work, by call time.Sleep.

Let's say the we have the following code in pymodule.go:

package parallel

import (
	"gopy"
	"time"
)

func updateList(list *py.List) {
	lock := py.NewLock()
	defer lock.Unlock()

	for i := int64(1); true; i++ {
		lock.UnblockThreads()
		time.Sleep(time.Second)
		lock.BlockThreads()

		p := py.NewInt64(i)
		list.Append(p)
		p.Decref()
	}
}

func example(args *py.Tuple) (py.Object, error) {
	lock := py.NewLock()
	defer lock.Unlock()

	var o py.Object

	err := py.ParseTuple(args, "O", &o)
	if err != nil {
		return nil, err
	}

	l, ok := o.(*py.List)
	if !ok {
		return nil, py.TypeError.Err("Expected *py.List, not %T", o)
	}

	go updateList(l)

	py.None.Incref()
	return py.None, nil
}

func init() {
	methods := []py.Method{
		{"example", example, "example function"},
	}

	_, err := py.InitModule("parallel", methods)
	if err != nil {
		panic(err)
	}
}

We can compile this into a CPython extension module parallel.so (the module name is the Go package name) with the following command:

> gopy pymodule.go

If we now run the following Python code:

import parallel
import time

x = []
parallel.example(x)

time.sleep(4)
print "x =", x

Then we get the following output:

x = [1,2,3,4]