Comments:"goPy - CPython Extension Modules"
URL:http://gopy.qur.me/extensions/examples.html
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:
packagesimpleimport("fmt""gopy")funcexample(args*py.Tuple)(py.Object,error){fmt.Printf("simple.example: %v\n",args)py.None.Incref()returnpy.None,nil}funcinit(){methods:=[]py.Method{{"example",example,"example function"},}_,err:=py.InitModule("simple",methods)iferr!=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:
If we now run the following Python code:
importsimplesimple.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:
packageparallelimport("gopy""time")funcupdateList(list*py.List){lock:=py.NewLock()deferlock.Unlock()fori:=int64(1);true;i++{lock.UnblockThreads()time.Sleep(time.Second)lock.BlockThreads()p:=py.NewInt64(i)list.Append(p)p.Decref()}}funcexample(args*py.Tuple)(py.Object,error){lock:=py.NewLock()deferlock.Unlock()varopy.Objecterr:=py.ParseTuple(args,"O",&o)iferr!=nil{returnnil,err}l,ok:=o.(*py.List)if!ok{returnnil,py.TypeError.Err("Expected *py.List, not %T",o)}goupdateList(l)py.None.Incref()returnpy.None,nil}funcinit(){methods:=[]py.Method{{"example",example,"example function"},}_,err:=py.InitModule("parallel",methods)iferr!=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:
If we now run the following Python code:
importparallelimporttimex=[]parallel.example(x)time.sleep(4)print"x =",x
Then we get the following output: