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 ¶
- Constants
- Variables
- func As[T any](v *Value, err error) (T, error)
- func Raise(typ, message string) error
- type Args
- type Exception
- type Func
- type Runtime
- func (rt *Runtime) Close() error
- func (rt *Runtime) Collect() int
- func (rt *Runtime) Define(name string, f Func) error
- func (rt *Runtime) Eval(source string) (*Value, error)
- func (rt *Runtime) Exec(source string) error
- func (rt *Runtime) ExecModule(module *Value, source, filename string) error
- func (rt *Runtime) Function(name string, f Func) (*Value, error)
- func (rt *Runtime) Get(name string) (*Value, error)
- func (rt *Runtime) Mount(directory, path string, readOnly bool) error
- func (rt *Runtime) RegisterModule(name string, init func(rt *Runtime, module *Value) error) error
- func (rt *Runtime) Set(name string, value any) error
- func (rt *Runtime) SetLoader(loader func(name string) (source string, ok bool))
- func (rt *Runtime) SetOptimize(level int)
- func (rt *Runtime) SetOutput(w io.Writer)
- func (rt *Runtime) SetStepLimit(limit uint)
- func (rt *Runtime) StepsUsed() uint
- func (rt *Runtime) ToValue(x any) (*Value, error)
- type Tuple
- type Value
- func (v *Value) Call(args ...any) (*Value, error)
- func (v *Value) CallKeywords(args []any, kwargs map[string]any) (*Value, error)
- func (v *Value) Decode(out any) error
- func (v *Value) GetAttr(name string) (*Value, error)
- func (v *Value) GetItem(key any) (*Value, error)
- func (v *Value) IsNone() bool
- func (v *Value) Iter() iter.Seq2[*Value, error]
- func (v *Value) Repr() (string, error)
- func (v *Value) Runtime() *Runtime
- func (v *Value) SetAttr(name string, item any) error
- func (v *Value) SetItem(key, item any) error
- func (v *Value) Str() (string, error)
- func (v *Value) String() string
- func (v *Value) Truth() bool
Examples ¶
Constants ¶
const Version = C.SPY_VERSION
Version is the engine version, as spy.h defines it.
Variables ¶
var ErrClosed = errors.New("spy: the runtime is closed")
ErrClosed is returned by every operation on a closed runtime.
Functions ¶
Types ¶
type Args ¶
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
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>
type Func ¶
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 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 (*Runtime) Close ¶
Close frees the context and every value in it. Values of a closed runtime return ErrClosed.
func (*Runtime) Define ¶
Define binds Runtime.Function as the global name.
func (*Runtime) ExecModule ¶
ExecModule runs source with module's namespace as its globals.
func (*Runtime) Function ¶
Function returns a builtin function named name that calls f. The engine keeps f until the function value is freed.
func (*Runtime) Mount ¶
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 ¶
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 ¶
Set converts value as by Runtime.ToValue and binds it to a global.
func (*Runtime) SetLoader ¶
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 ¶
SetOptimize sets the optimization level, as python -O (1) and -OO (2).
func (*Runtime) SetOutput ¶
SetOutput sends everything engine code prints to w, os.Stdout by default. With a nil w, printing raises OSError.
func (*Runtime) SetStepLimit ¶
SetStepLimit bounds the evaluation steps of each top-level Eval or Exec; 0 is unlimited. Exceeding it raises RuntimeError.
func (*Runtime) StepsUsed ¶ added in v0.5.0
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 ¶
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 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.
func (*Value) CallKeywords ¶
CallKeywords calls the value with positional and keyword arguments.
func (*Value) Decode ¶
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) Iter ¶
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