rage

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package rage provides a public API for embedding the RAGE Python runtime in Go applications.

Quick Start

The simplest way to run Python code:

result, err := rage.Run(`print("Hello, World!")`)
if err != nil {
    log.Fatal(err)
}

To evaluate an expression and get the result:

result, err := rage.Eval(`1 + 2 * 3`)
if err != nil {
    log.Fatal(err)
}
fmt.Println(result) // 7

Using State for More Control

For more complex scenarios, create a State:

state := rage.NewState()
defer state.Close()

// Set variables accessible from Python
state.SetGlobal("name", rage.String("World"))
state.SetGlobal("count", rage.Int(42))

// Run Python code
_, err := state.Run(`
    greeting = "Hello, " + name + "!"
    result = count * 2
`)
if err != nil {
    log.Fatal(err)
}

// Get variables set by Python
greeting := state.GetGlobal("greeting")
fmt.Println(greeting) // Hello, World!

Controlling Stdlib Modules

By default, NewState() enables all stdlib modules. For more control over which modules are available, use NewStateWithModules or NewBareState:

// Create state with only specific modules
state := rage.NewStateWithModules(
    rage.WithModule(rage.ModuleMath),
    rage.WithModule(rage.ModuleString),
)
defer state.Close()

// Or enable multiple modules at once
state := rage.NewStateWithModules(
    rage.WithModules(rage.ModuleMath, rage.ModuleString, rage.ModuleTime),
)

// Create a bare state with no modules, then enable them later
state := rage.NewBareState()
defer state.Close()
state.EnableModule(rage.ModuleMath)
state.EnableModules(rage.ModuleString, rage.ModuleTime)

// Enable all modules on an existing state
state.EnableAllModules()

Available modules:

rage.ModuleMath        // math module (sin, cos, sqrt, etc.)
rage.ModuleRandom      // random module (random, randint, choice, etc.)
rage.ModuleString      // string module (ascii_letters, digits, etc.)
rage.ModuleSys         // sys module (version, platform, etc.)
rage.ModuleTime        // time module (time, sleep, etc.)
rage.ModuleRe          // re module (match, search, findall, etc.)
rage.ModuleCollections // collections module (Counter, defaultdict, etc.)

Registering Go Functions

You can make Go functions callable from Python:

state := rage.NewState()
defer state.Close()

// Register a function
state.Register("greet", func(s *rage.State, args ...rage.Value) rage.Value {
    name, _ := rage.AsString(args[0])
    return rage.String("Hello, " + name + "!")
})

// Call it from Python
result, _ := state.Run(`message = greet("World")`)
fmt.Println(state.GetGlobal("message")) // Hello, World!

Working with Values

The rage.Value interface wraps Python values. Use constructors and type assertions:

// Create values
intVal := rage.Int(42)
strVal := rage.String("hello")
listVal := rage.List(rage.Int(1), rage.Int(2), rage.Int(3))
dictVal := rage.Dict("name", rage.String("Alice"), "age", rage.Int(30))

// Convert from Go values
val := rage.FromGo(map[string]any{"key": "value"})

// Type checking
if rage.IsInt(val) {
    n, _ := rage.AsInt(val)
    fmt.Println(n)
}

// Get underlying Go value
goVal := val.GoValue()

Timeouts and Cancellation

Execute code with timeouts to prevent infinite loops:

result, err := rage.RunWithTimeout(`
    while True:
        pass  # infinite loop
`, 5*time.Second)
// Returns error after 5 seconds

Or use context for cancellation:

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

state := rage.NewState()
result, err := state.RunWithContext(ctx, `some_long_running_code()`)

Compilation and Execution

For repeated execution, compile once and run multiple times:

state := rage.NewState()
defer state.Close()

code, err := state.Compile(`result = x * 2`, "multiply.py")
if err != nil {
    log.Fatal(err)
}

// Execute multiple times with different inputs
for i := 0; i < 10; i++ {
    state.SetGlobal("x", rage.Int(int64(i)))
    state.Execute(code)
    result := state.GetGlobal("result")
    fmt.Println(result)
}

Error Handling

Compilation errors are returned as *CompileErrors:

_, err := rage.Run(`invalid python syntax here`)
if compErr, ok := err.(*rage.CompileErrors); ok {
    for _, e := range compErr.Errors {
        fmt.Println(e)
    }
}

Runtime errors are returned as standard errors.

Thread Safety

Each State is NOT safe for concurrent use. Create separate States for concurrent execution, or use appropriate synchronization.

Package rage provides a public API for embedding the RAGE Python runtime in Go applications.

Basic usage:

// Run Python code and get a result
result, err := rage.Run(`x = 1 + 2`)

// Create a state for more control
state := rage.NewState()
defer state.Close()
state.SetGlobal("name", rage.String("World"))
result, err := state.Run(`greeting = "Hello, " + name`)
greeting := state.GetGlobal("greeting")

The API is inspired by gopher-lua for familiarity.

Index

Constants

This section is empty.

Variables

AllBuiltins contains all opt-in builtins.

AllModules is a convenience slice containing all available modules.

View Source
var ExecutionBuiltins = []Builtin{
	BuiltinCompile,
	BuiltinExec,
	BuiltinEval,
}

ExecutionBuiltins contains all code execution builtins (compile, exec, eval). These allow arbitrary code execution and should be enabled with caution.

ReflectionBuiltins contains all reflection-related builtins (repr, dir, globals, locals, vars). These are relatively safe introspection functions.

Functions

func AsBool

func AsBool(v Value) (bool, bool)

AsBool returns the bool value or false if not a bool

func AsComplex

func AsComplex(v Value) (real, imag float64, ok bool)

AsComplex returns the complex value or (0,0) if not a complex

func AsDict

func AsDict(v Value) (map[string]Value, bool)

AsDict returns the dict value or nil if not a dict

func AsFloat

func AsFloat(v Value) (float64, bool)

AsFloat returns the float value or 0 if not a float

func AsInt

func AsInt(v Value) (int64, bool)

AsInt returns the int value or 0 if not an int

func AsString

func AsString(v Value) (string, bool)

AsString returns the string value or "" if not a string

func AsUserData

func AsUserData(v Value) (any, bool)

AsUserData returns the userdata value or nil if not userdata

func IsBool

func IsBool(v Value) bool

IsBool returns true if the value is a bool

func IsComplex

func IsComplex(v Value) bool

IsComplex returns true if the value is a complex

func IsDict

func IsDict(v Value) bool

IsDict returns true if the value is a dict

func IsFloat

func IsFloat(v Value) bool

IsFloat returns true if the value is a float

func IsInt

func IsInt(v Value) bool

IsInt returns true if the value is an int

func IsList

func IsList(v Value) bool

IsList returns true if the value is a list

func IsNone

func IsNone(v Value) bool

IsNone returns true if the value is None

func IsString

func IsString(v Value) bool

IsString returns true if the value is a string

func IsTuple

func IsTuple(v Value) bool

IsTuple returns true if the value is a tuple

func IsUserData

func IsUserData(v Value) bool

IsUserData returns true if the value is userdata

Types

type BoolValue

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

BoolValue represents a Python bool

func (BoolValue) Bool

func (v BoolValue) Bool() bool

func (BoolValue) GoValue

func (v BoolValue) GoValue() any

func (BoolValue) String

func (v BoolValue) String() string

func (BoolValue) Type

func (v BoolValue) Type() string

type Builtin

type Builtin int

Builtin represents an opt-in builtin function that can be enabled. These builtins provide reflection and code execution capabilities that are not enabled by default for security reasons.

const (
	BuiltinRepr Builtin = iota
	BuiltinDir
	BuiltinGlobals
	BuiltinLocals
	BuiltinVars
	BuiltinCompile
	BuiltinExec
	BuiltinEval
)

type Code

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

Code represents compiled Python bytecode.

func (*Code) Name

func (c *Code) Name() string

Name returns the name of the compiled code (module/function name).

type CompileErrors

type CompileErrors struct {
	Errors []error
}

CompileErrors wraps multiple compilation errors.

func (*CompileErrors) Error

func (e *CompileErrors) Error() string

func (*CompileErrors) Unwrap

func (e *CompileErrors) Unwrap() error

Unwrap returns the first error for errors.Is/As compatibility.

type ComplexValue

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

ComplexValue represents a Python complex

func (ComplexValue) GoValue

func (v ComplexValue) GoValue() any

func (ComplexValue) Imag

func (v ComplexValue) Imag() float64

func (ComplexValue) Real

func (v ComplexValue) Real() float64

func (ComplexValue) String

func (v ComplexValue) String() string

func (ComplexValue) Type

func (v ComplexValue) Type() string

type DictValue

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

DictValue represents a Python dict

func (DictValue) Get

func (v DictValue) Get(key string) Value

func (DictValue) GoValue

func (v DictValue) GoValue() any

func (DictValue) Items

func (v DictValue) Items() map[string]Value

func (DictValue) Len

func (v DictValue) Len() int

func (DictValue) String

func (v DictValue) String() string

func (DictValue) Type

func (v DictValue) Type() string

type FloatValue

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

FloatValue represents a Python float

func (FloatValue) Float

func (v FloatValue) Float() float64

func (FloatValue) GoValue

func (v FloatValue) GoValue() any

func (FloatValue) String

func (v FloatValue) String() string

func (FloatValue) Type

func (v FloatValue) Type() string

type FunctionValue

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

FunctionValue represents a Python function (for introspection)

func (FunctionValue) GoValue

func (v FunctionValue) GoValue() any

func (FunctionValue) Name

func (v FunctionValue) Name() string

func (FunctionValue) String

func (v FunctionValue) String() string

func (FunctionValue) Type

func (v FunctionValue) Type() string

type GoFunc

type GoFunc func(s *State, args ...Value) Value

GoFunc is the signature for Go functions callable from Python.

type IntValue

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

IntValue represents a Python int

func (IntValue) GoValue

func (v IntValue) GoValue() any

func (IntValue) Int

func (v IntValue) Int() int64

func (IntValue) String

func (v IntValue) String() string

func (IntValue) Type

func (v IntValue) Type() string

type ListValue

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

ListValue represents a Python list

func (ListValue) Get

func (v ListValue) Get(i int) Value

func (ListValue) GoValue

func (v ListValue) GoValue() any

func (ListValue) Items

func (v ListValue) Items() []Value

func (ListValue) Len

func (v ListValue) Len() int

func (ListValue) String

func (v ListValue) String() string

func (ListValue) Type

func (v ListValue) Type() string

type Module

type Module int

Module represents a standard library module that can be enabled.

const (
	ModuleMath Module = iota
	ModuleRandom
	ModuleString
	ModuleSys
	ModuleTime
	ModuleRe
	ModuleCollections
	ModuleAsyncio
	ModuleIO // File I/O
	ModuleJSON
	ModuleOS
	ModuleDatetime
	ModuleTyping
	ModuleCSV
	ModuleItertools
	ModuleFunctools
	ModuleBase64
	ModuleAbc
	ModuleDataclasses
	ModuleCopy
	ModuleOperator
)

type NoneValue

type NoneValue struct{}

NoneValue represents Python's None

func (NoneValue) GoValue

func (v NoneValue) GoValue() any

func (NoneValue) String

func (v NoneValue) String() string

func (NoneValue) Type

func (v NoneValue) Type() string

type State

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

State represents a Python execution state. It wraps the VM and provides a clean API for running Python code.

func NewBareState

func NewBareState() *State

NewBareState creates a new Python execution state with no stdlib modules enabled. Use EnableModule or EnableAllModules to enable modules after creation.

func NewState

func NewState() *State

NewState creates a new Python execution state with all stdlib modules enabled. This is a convenience function equivalent to NewStateWithModules(WithAllModules()).

func NewStateWithModules

func NewStateWithModules(opts ...StateOption) *State

NewStateWithModules creates a new Python execution state with the specified options.

Example:

// Create state with only math and string modules
state := rage.NewStateWithModules(
    rage.WithModule(rage.ModuleMath),
    rage.WithModule(rage.ModuleString),
)

// Or use WithModules for multiple at once
state := rage.NewStateWithModules(
    rage.WithModules(rage.ModuleMath, rage.ModuleString, rage.ModuleTime),
)

// Enable all modules
state := rage.NewStateWithModules(rage.WithAllModules())

func (*State) Close

func (s *State) Close()

Close releases resources associated with the state. Always call this when done with the state. After Close is called, the state should not be used.

func (*State) Compile

func (s *State) Compile(source, filename string) (*Code, error)

Compile compiles Python source code without executing it. The compiled code can be executed later with Execute.

func (*State) EnableAllBuiltins

func (s *State) EnableAllBuiltins()

EnableAllBuiltins enables all opt-in builtins.

func (*State) EnableAllModules

func (s *State) EnableAllModules()

EnableAllModules enables all available stdlib modules.

func (*State) EnableBuiltin

func (s *State) EnableBuiltin(b Builtin)

EnableBuiltin enables a specific opt-in builtin function. This can be called after state creation to add builtins.

func (*State) EnableBuiltins

func (s *State) EnableBuiltins(builtins ...Builtin)

EnableBuiltins enables multiple opt-in builtin functions.

func (*State) EnableExecutionBuiltins

func (s *State) EnableExecutionBuiltins()

EnableExecutionBuiltins enables all execution builtins (compile, exec, eval).

func (*State) EnableModule

func (s *State) EnableModule(m Module)

EnableModule enables a specific stdlib module. This can be called after state creation to add modules.

func (*State) EnableModules

func (s *State) EnableModules(modules ...Module)

EnableModules enables multiple stdlib modules.

func (*State) EnableReflectionBuiltins

func (s *State) EnableReflectionBuiltins()

EnableReflectionBuiltins enables all reflection builtins (repr, dir, globals, locals, vars).

func (*State) EnabledBuiltins

func (s *State) EnabledBuiltins() []Builtin

EnabledBuiltins returns a slice of all enabled builtins.

func (*State) EnabledModules

func (s *State) EnabledModules() []Module

EnabledModules returns a slice of all enabled modules.

func (*State) Execute

func (s *State) Execute(code *Code) (Value, error)

Execute runs previously compiled code.

func (*State) ExecuteWithTimeout

func (s *State) ExecuteWithTimeout(code *Code, timeout time.Duration) (Value, error)

ExecuteWithTimeout runs previously compiled code with a timeout.

func (*State) GetGlobal

func (s *State) GetGlobal(name string) Value

GetGlobal retrieves a global variable set by Python code.

func (*State) GetGlobals

func (s *State) GetGlobals() map[string]Value

GetGlobals returns all global variables as a map.

func (*State) GetModuleAttr

func (s *State) GetModuleAttr(moduleName, attrName string) Value

GetModuleAttr retrieves an attribute from an imported module. Returns nil if the module doesn't exist or the attribute isn't found.

func (*State) IsBuiltinEnabled

func (s *State) IsBuiltinEnabled(b Builtin) bool

IsBuiltinEnabled returns true if the specified builtin is enabled.

func (*State) IsModuleEnabled

func (s *State) IsModuleEnabled(m Module) bool

IsModuleEnabled returns true if the specified module is enabled.

func (*State) Register

func (s *State) Register(name string, fn GoFunc)

Register registers a Go function that can be called from Python.

Example:

state.Register("greet", func(s *rage.State, args ...rage.Value) rage.Value {
    name := args[0].String()
    return rage.String("Hello, " + name + "!")
})

Then in Python: greet("World")

func (*State) RegisterBuiltin

func (s *State) RegisterBuiltin(name string, fn GoFunc)

RegisterBuiltin registers a Go function as a builtin.

func (*State) RegisterPythonModule

func (s *State) RegisterPythonModule(moduleName, source string) error

RegisterPythonModule compiles and registers Python source code as an importable module. The module can then be imported using "import moduleName" or "from moduleName import ...".

func (*State) Run

func (s *State) Run(source string) (Value, error)

Run compiles and executes Python source code. Returns the result of the last expression or nil.

func (*State) RunWithContext

func (s *State) RunWithContext(ctx context.Context, source string) (Value, error)

RunWithContext executes Python code with a context for cancellation.

func (*State) RunWithFilename

func (s *State) RunWithFilename(source, filename string) (Value, error)

RunWithFilename compiles and executes Python source code with a filename for error messages.

func (*State) RunWithTimeout

func (s *State) RunWithTimeout(source string, timeout time.Duration) (Value, error)

RunWithTimeout executes Python code with a timeout.

func (*State) SetGlobal

func (s *State) SetGlobal(name string, value Value)

SetGlobal sets a global variable accessible from Python code.

type StateOption

type StateOption func(*stateConfig)

StateOption is a functional option for configuring State creation.

func WithAllBuiltins

func WithAllBuiltins() StateOption

WithAllBuiltins enables all opt-in builtins.

func WithAllModules

func WithAllModules() StateOption

WithAllModules enables all stdlib modules.

func WithBuiltin

func WithBuiltin(b Builtin) StateOption

WithBuiltin enables a specific opt-in builtin function.

func WithBuiltins

func WithBuiltins(builtins ...Builtin) StateOption

WithBuiltins enables multiple opt-in builtin functions.

func WithExecutionBuiltins

func WithExecutionBuiltins() StateOption

WithExecutionBuiltins enables all execution builtins (compile, exec, eval).

func WithModule

func WithModule(m Module) StateOption

WithModule enables a specific stdlib module.

func WithModules

func WithModules(modules ...Module) StateOption

WithModules enables multiple stdlib modules.

func WithReflectionBuiltins

func WithReflectionBuiltins() StateOption

WithReflectionBuiltins enables all reflection builtins (repr, dir, globals, locals, vars).

type StringValue

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

StringValue represents a Python str

func (StringValue) GoValue

func (v StringValue) GoValue() any

func (StringValue) Str

func (v StringValue) Str() string

func (StringValue) String

func (v StringValue) String() string

func (StringValue) Type

func (v StringValue) Type() string

type TupleValue

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

TupleValue represents a Python tuple

func (TupleValue) Get

func (v TupleValue) Get(i int) Value

func (TupleValue) GoValue

func (v TupleValue) GoValue() any

func (TupleValue) Items

func (v TupleValue) Items() []Value

func (TupleValue) Len

func (v TupleValue) Len() int

func (TupleValue) String

func (v TupleValue) String() string

func (TupleValue) Type

func (v TupleValue) Type() string

type UserDataValue

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

UserDataValue wraps arbitrary Go values

func (UserDataValue) GoValue

func (v UserDataValue) GoValue() any

func (UserDataValue) String

func (v UserDataValue) String() string

func (UserDataValue) Type

func (v UserDataValue) Type() string

type Value

type Value interface {
	// Type returns the Python type name (e.g., "int", "str", "list")
	Type() string

	// String returns a string representation of the value
	String() string

	// GoValue returns the underlying Go value
	GoValue() any
	// contains filtered or unexported methods
}

Value represents a Python value. Use the type assertion or helper methods to access the underlying Go value.

var (
	True  Value = BoolValue{/* contains filtered or unexported fields */}
	False Value = BoolValue{/* contains filtered or unexported fields */}
)

True and False are the singleton bool values

var None Value = NoneValue{}

None is the singleton None value

func AsList

func AsList(v Value) ([]Value, bool)

AsList returns the list value or nil if not a list

func AsTuple

func AsTuple(v Value) ([]Value, bool)

AsTuple returns the tuple value or nil if not a tuple

func Bool

func Bool(v bool) Value

Bool creates a Python bool value

func Complex

func Complex(real, imag float64) Value

Complex creates a Python complex value

func Dict

func Dict(pairs ...any) Value

Dict creates a Python dict from string keys and Values

func Eval

func Eval(expr string) (Value, error)

Eval evaluates a Python expression and returns the result. Unlike Run, this expects an expression, not statements.

func Float

func Float(v float64) Value

Float creates a Python float value

func FromGo

func FromGo(v any) Value

FromGo converts a Go value to a Python Value

func Int

func Int(v int64) Value

Int creates a Python int value

func List

func List(items ...Value) Value

List creates a Python list from Values

func Run

func Run(source string) (Value, error)

Run is a convenience function that creates a temporary state, runs the code, and returns the result.

func RunWithTimeout

func RunWithTimeout(source string, timeout time.Duration) (Value, error)

RunWithTimeout runs Python code with a timeout.

func String

func String(v string) Value

String creates a Python str value

func Tuple

func Tuple(items ...Value) Value

Tuple creates a Python tuple from Values

func UserData

func UserData(v any) Value

UserData wraps a Go value for use in Python

Jump to

Keyboard shortcuts

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