spy

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package spy embeds Small Python, a small Python 3.15 engine written in C11, in a Go program.

The engine is compiled from source by cgo, so there is nothing to install beyond a C compiler. A Runtime owns one engine context; every Value holds a reference into it, which the garbage collector releases.

rt, err := spy.New()
if err != nil {
	return err
}
defer rt.Close()
rt.Define("add", func(rt *spy.Runtime, args spy.Args) (any, error) {
	var a, b int
	if err := args.Scan(&a, &b); err != nil {
		return nil, err
	}
	return a + b, nil
})
n, err := spy.As[int](rt.Eval("add(40, 2)"))

The engine runs in this process, so it is only as trustworthy as its C code. To run untrusted code, use package worker, which runs each runtime in its own sandboxed process.

Example
package main

import (
	"fmt"

	"github.com/soasme/small-python/go/spy"
)

func main() {
	rt, err := spy.New()
	if err != nil {
		panic(err)
	}
	defer rt.Close()
	rt.Define("add", func(rt *spy.Runtime, args spy.Args) (any, error) {
		var a, b int
		if err := args.Scan(&a, &b); err != nil {
			return nil, err
		}
		return a + b, nil
	})
	n, err := spy.As[int](rt.Eval("add(40, 2)"))
	fmt.Println(n, err)
}
Output:
42 <nil>

Index

Examples

Constants

View Source
const Version = C.SPY_VERSION

Version is the engine version, as spy.h defines it.

Variables

View Source
var ErrClosed = errors.New("spy: the runtime is closed")

ErrClosed is returned by every operation on a closed runtime.

View Source
var ErrRunning = errors.New("spy: cannot close the runtime while it runs a host function")

ErrRunning is Close's error inside one of the runtime's callbacks.

Functions

func As

func As[T any](v *Value, err error) (T, error)

As decodes the result of an operation into a T, passing its error on:

n, err := spy.As[int](rt.Eval("6 * 7"))

func Raise

func Raise(typ, message string) error

Raise returns an exception for a host function to fail with: the engine raises the builtin class typ with message. Any other error a host function returns raises RuntimeError with its text.

Types

type Args

type Args struct {
	Positional []*Value
	Keywords   map[string]*Value
}

Args are the arguments of a call to a host function.

Example
package main

import (
	"fmt"

	"github.com/soasme/small-python/go/spy"
)

func main() {
	rt, _ := spy.New()
	defer rt.Close()
	rt.Define("greet", func(rt *spy.Runtime, args spy.Args) (any, error) {
		var name string
		if err := args.Scan(&name); err != nil {
			return nil, err
		}
		end := "!"
		if v := args.Keywords["end"]; v != nil {
			if err := v.Decode(&end); err != nil {
				return nil, err
			}
		}
		return "hello " + name + end, nil
	})
	s, _ := spy.As[string](rt.Eval("greet('spy', end='?')"))
	fmt.Println(s)
	_, err := rt.Eval("greet()")
	fmt.Println(err)
}
Output:
hello spy?
TypeError: expected 1 argument, got 0

func (Args) Scan

func (a Args) Scan(dest ...any) error

Scan decodes the positional arguments into dest, one each, after checking their count.

type Exception

type Exception struct {
	// Type is the class name, qualified by its module unless it is a builtin.
	Type string
	// Message is the text CPython's traceback shows after the type.
	Message string
	// Filename and Line say where it was raised, when it came from the engine.
	Filename string
	Line     int
}

An Exception is an engine exception, raised by engine code or by Go.

Exceptions cross between Go and the engine by type name and message: one that escapes into Go is copied into an *Exception and cleared, and a host function returning one raises a new exception with the same type name and message.

Example
package main

import (
	"fmt"

	"github.com/soasme/small-python/go/spy"
)

func main() {
	rt, _ := spy.New()
	defer rt.Close()
	err := rt.Exec("x = 1\nraise ValueError('bad input')")
	if e, ok := err.(*spy.Exception); ok {
		fmt.Println(e.Type, e.Message, e.Line)
	}
	rt.Define("lookup", func(*spy.Runtime, spy.Args) (any, error) {
		return nil, spy.Raise("KeyError", "missing")
	})
	err = rt.Exec("try:\n    lookup()\nexcept KeyError as e:\n    print('caught', repr(e))")
	fmt.Println(err)
}
Output:
ValueError bad input 2
caught KeyError('missing')
<nil>

func (*Exception) Error

func (e *Exception) Error() string

type Func

type Func func(rt *Runtime, args Args) (any, error)

Func is a host function. It receives the runtime it runs in and the call's arguments; its result converts as by Runtime.ToValue, and its error raises an exception (see Raise).

type Limit added in v0.7.0

type Limit int

A Limit names one of the bounds SetLimit sets.

const (
	LimitSteps     Limit = C.SPY_LIMIT_STEPS      // steps of each top-level call; 0 is unlimited
	LimitMemory    Limit = C.SPY_LIMIT_MEMORY     // bytes the engine holds; 0 is unlimited
	LimitOutput    Limit = C.SPY_LIMIT_OUTPUT     // bytes each top-level call prints; 0 is unlimited
	LimitRecursion Limit = C.SPY_LIMIT_RECURSION  // Python call depth
	LimitIntDigits Limit = C.SPY_LIMIT_INT_DIGITS // int-str conversion digits; 0 is unlimited
	LimitStack     Limit = C.SPY_LIMIT_STACK      // bytes of C stack the engine may use
)

type Runtime

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

A Runtime is one independent engine context. It is not safe for concurrent use; inside a host function, the runtime it receives is the same one.

func New

func New() (*Runtime, error)

New returns a runtime with the standard module sys.

func NewBare

func NewBare() (*Runtime, error)

NewBare returns a runtime with only the language core and its builtins.

func (*Runtime) CheckPolicy added in v0.7.0

func (rt *Runtime) CheckPolicy(event string, args ...any) error

CheckPolicy asks the policy about an event of the host's own, such as a network request from a Go function; nil when allowed or no policy is set.

func (*Runtime) Close

func (rt *Runtime) Close() error

Close frees the context and every value in it. Values of a closed runtime return ErrClosed. Closing from a host function, module initializer, loader, output, or policy of the runtime fails with ErrRunning, as the engine is running beneath it.

func (*Runtime) Collect

func (rt *Runtime) Collect() int

Collect runs the cycle collector and returns the number of values freed.

func (*Runtime) Define

func (rt *Runtime) Define(name string, f Func) error

Define binds Runtime.Function as the global name.

func (*Runtime) Eval

func (rt *Runtime) Eval(source string) (*Value, error)

Eval runs source and returns the value of its last expression statement.

func (*Runtime) Exec

func (rt *Runtime) Exec(source string) error

Exec runs source for its effects.

func (*Runtime) ExecModule

func (rt *Runtime) ExecModule(module *Value, source, filename string) error

ExecModule runs source with module's namespace as its globals.

func (*Runtime) Function

func (rt *Runtime) Function(name string, f Func) (*Value, error)

Function returns a builtin function named name that calls f. The engine keeps f until the function value is freed.

func (*Runtime) Get

func (rt *Runtime) Get(name string) (*Value, error)

Get reads a global.

func (*Runtime) Limit added in v0.7.0

func (rt *Runtime) Limit(limit Limit) uint

Limit returns a limit's current value.

func (*Runtime) LoadNative added in v0.7.0

func (rt *Runtime) LoadNative(name, path string) error

LoadNative opens the shared library at path, a native module built with spy-module.h, and registers it as name, so that `import name` runs its init. The policy is asked first, with "dlopen" (name, path). A library that fails to load is closed and raises ImportError; one that loads stays open for the life of the process. Its code runs outside the policy and the limits, with the process's rights.

func (*Runtime) Mount

func (rt *Runtime) Mount(directory, path string, readOnly bool) error

Mount lets open() reach directory at the absolute engine path path, or at the directory's own resolved path when path is empty.

Example
package main

import (
	"fmt"
	"os"

	"github.com/soasme/small-python/go/spy"
)

func main() {
	dir, _ := os.MkdirTemp("", "spy")
	defer os.RemoveAll(dir)
	os.WriteFile(dir+"/notes.txt", []byte("hello from the host\n"), 0o644)
	rt, _ := spy.New()
	defer rt.Close()
	rt.Mount(dir, "/data", true)
	s, _ := spy.As[string](rt.Eval("open('/data/notes.txt').read().strip()"))
	fmt.Println(s)
	_, err := rt.Eval("open('/data/new.txt', 'w')")
	fmt.Println(err.(*spy.Exception).Type)
}
Output:
hello from the host
OSError

func (*Runtime) RegisterModule

func (rt *Runtime) RegisterModule(name string, init func(rt *Runtime, module *Value) error) error

RegisterModule makes `import name` create a module and call init to fill it, as QuickJS's JS_NewCModule. Registering a name again replaces init.

Example
package main

import (
	"fmt"
	"strings"

	"github.com/soasme/small-python/go/spy"
)

func main() {
	rt, _ := spy.New()
	defer rt.Close()
	rt.RegisterModule("config", func(rt *spy.Runtime, module *spy.Value) error {
		if err := module.SetAttr("region", "eu"); err != nil {
			return err
		}
		return rt.ExecModule(module, "def describe(): return 'region ' + region", "<config>")
	})
	rt.SetLoader(func(name string) (string, bool) {
		if name == "shapes" {
			return "def area(w, h): return w * h\n", true
		}
		return "", false
	})
	var out strings.Builder
	rt.SetOutput(&out)
	err := rt.Exec("import config, shapes\nprint(config.describe(), shapes.area(3, 4))")
	fmt.Print(out.String(), err)
}
Output:
region eu 12
<nil>

func (*Runtime) Set

func (rt *Runtime) Set(name string, value any) error

Set converts value as by Runtime.ToValue and binds it to a global.

func (*Runtime) SetLimit added in v0.7.0

func (rt *Runtime) SetLimit(limit Limit, value uint) error

SetLimit sets one limit. A spent step, memory or output limit stops the call with RuntimeError (MemoryError for memory) that no handler catches.

func (*Runtime) SetLoader

func (rt *Runtime) SetLoader(loader func(name string) (source string, ok bool))

SetLoader maps a module name to its source, or reports that there is none. For `import pkg.mod` it is asked for pkg.mod.__init__ (a package), then pkg.mod, then pkg.mod.__namespace__ (a namespace package).

func (*Runtime) SetOptimize

func (rt *Runtime) SetOptimize(level int)

SetOptimize sets the optimization level, as python -O (1) and -OO (2).

func (*Runtime) SetOutput

func (rt *Runtime) SetOutput(w io.Writer)

SetOutput sends everything engine code prints to w, os.Stdout by default. With a nil w, printing raises OSError.

func (*Runtime) SetPolicy added in v0.7.0

func (rt *Runtime) SetPolicy(policy func(event string, args []*Value) error)

SetPolicy asks policy before open, a module's first import, exec, eval or compile of a string, input, and LoadNative, with the event's name ("open", "import", "exec", "input", "dlopen") and arguments. A non-nil error refuses: an *Exception raises its type, any other error PermissionError. nil removes the policy.

func (*Runtime) StepsUsed added in v0.5.0

func (rt *Runtime) StepsUsed() uint

StepsUsed returns the steps the running or last top-level Eval or Exec spent; calls spend only while a step limit is set.

func (*Runtime) ToValue

func (rt *Runtime) ToValue(x any) (*Value, error)

ToValue converts a Go value into an engine value:

nil, a nil pointer          None
bool                        bool
integers                    int (beyond int64: OverflowError)
float32, float64            float
string                      str
[]byte                      bytes
Tuple                       tuple
other slices and arrays     list
maps                        dict, in sorted key order
structs                     dict of the exported fields, named by a
                            `spy:"name"` tag; `spy:"-"` skips a field
pointers                    what they point to
*Value                      itself (of this runtime only)
Func                        a builtin function

Decoding is the reverse; it accepts an int for a float, any iterable for a slice, and any mapping for a map or struct, whose unknown keys it ignores. Into an any it gives nil, bool, int64, float64, string, []byte, []any for a list, Tuple, and map[any]any for a dict, and a *Value for anything else, including dict keys that are not of those scalar types.

type Tuple

type Tuple []any

Tuple converts to a tuple, and a tuple decodes to it in an any.

type Value

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

A Value is a reference to an engine value. The garbage collector releases it once it is unreachable; it never outlives its runtime's Close.

The engine borrows ptr while a method runs, and a host function it calls may release what the collector dropped, so each method keeps its value alive until it returns (tests/tla/SpyGo.tla).

func (*Value) Call

func (v *Value) Call(args ...any) (*Value, error)

Call calls the value with positional arguments.

func (*Value) CallKeywords

func (v *Value) CallKeywords(args []any, kwargs map[string]any) (*Value, error)

CallKeywords calls the value with positional and keyword arguments.

func (*Value) Decode

func (v *Value) Decode(out any) error

Decode stores the value in the Go value out points to; see Runtime.ToValue for the correspondence.

Example
package main

import (
	"fmt"

	"github.com/soasme/small-python/go/spy"
)

func main() {
	type User struct {
		Name  string   `spy:"name"`
		Roles []string `spy:"roles"`
		Admin bool     `spy:"-"`
	}
	rt, _ := spy.New()
	defer rt.Close()
	rt.Set("user", User{Name: "ada", Roles: []string{"dev"}})
	v, _ := rt.Eval("user | {'name': user['name'].title(), 'roles': user['roles'] + ['ops']}")
	var u User
	err := v.Decode(&u)
	fmt.Printf("%+v %v\n", u, err)
}
Output:
{Name:Ada Roles:[dev ops] Admin:false} <nil>

func (*Value) GetAttr

func (v *Value) GetAttr(name string) (*Value, error)

GetAttr is getattr(value, name).

func (*Value) GetItem

func (v *Value) GetItem(key any) (*Value, error)

GetItem is value[key].

func (*Value) IsNone

func (v *Value) IsNone() bool

IsNone reports whether the value is None.

func (*Value) Iter

func (v *Value) Iter() iter.Seq2[*Value, error]

Iter iterates the value as a for loop does, yielding each item or the error that ended the iteration.

Example
package main

import (
	"fmt"

	"github.com/soasme/small-python/go/spy"
)

func main() {
	rt, _ := spy.New()
	defer rt.Close()
	squares, _ := rt.Eval("(n * n for n in range(4))")
	for v, err := range squares.Iter() {
		n, err := spy.As[int](v, err)
		if err != nil {
			panic(err)
		}
		fmt.Print(n, " ")
	}
	fmt.Println()
}
Output:
0 1 4 9

func (*Value) Repr

func (v *Value) Repr() (string, error)

Repr is repr(value).

func (*Value) Runtime

func (v *Value) Runtime() *Runtime

Runtime returns the runtime the value belongs to.

func (*Value) SetAttr

func (v *Value) SetAttr(name string, item any) error

SetAttr is setattr(value, name, item).

func (*Value) SetItem

func (v *Value) SetItem(key, item any) error

SetItem is value[key] = item.

func (*Value) Str

func (v *Value) Str() (string, error)

Str is str(value).

func (*Value) String

func (v *Value) String() string

String is str(value), or a placeholder naming the error.

func (*Value) Truth

func (v *Value) Truth() (bool, error)

Truth is Python truth, as bool(value).

Jump to

Keyboard shortcuts

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