Writing a Python extension in Go (Golang)

Update 2015: possible as of Go 1.5 https://blog.filippo.io/building-python-modules-with-go-1-5/

with Go 1.5 you can build .so objects and import them as Python modules, running Go code (instead of C) directly from Python.

See also https://github.com/go-python/gopy

gopy generates a CPython extension module from a go package.


Unfortunately, this is not currently possible. Go can run C code (and that C code can then call back into Go), but the main function has to be in Go, so the Go runtime can set things up.


I've written an extension to setuptools which allows you to write cpython extensions that interface with go: https://github.com/asottile/setuptools-golang

There's a couple example extensions here:

  • https://github.com/asottile/setuptools-golang-examples
  • https://github.com/asottile/dockerfile

The neat thing is these can be installed just like any other pip package and support both cpython and pypy.

PEP 513 manylinux1 wheels can also be built to provide pre-built wheels via the setuptools-golang-build-manylinux-wheels tool.

The approach is nearly identical to the one in @ColonelPanic's answer but uses some additional tricks to enable python2 + python3 compatibility.