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 ¶
- Variables
- func AsBool(v Value) (bool, bool)
- func AsComplex(v Value) (real, imag float64, ok bool)
- func AsDict(v Value) (map[string]Value, bool)
- func AsFloat(v Value) (float64, bool)
- func AsInt(v Value) (int64, bool)
- func AsString(v Value) (string, bool)
- func AsUserData(v Value) (any, bool)
- func IsBool(v Value) bool
- func IsComplex(v Value) bool
- func IsDict(v Value) bool
- func IsFloat(v Value) bool
- func IsInt(v Value) bool
- func IsList(v Value) bool
- func IsNone(v Value) bool
- func IsString(v Value) bool
- func IsTuple(v Value) bool
- func IsUserData(v Value) bool
- type BoolValue
- type Builtin
- type Code
- type CompileErrors
- type ComplexValue
- type DictValue
- type FloatValue
- type FunctionValue
- type GoFunc
- type IntValue
- type ListValue
- type Module
- type NoneValue
- type State
- func (s *State) Close()
- func (s *State) Compile(source, filename string) (*Code, error)
- func (s *State) EnableAllBuiltins()
- func (s *State) EnableAllModules()
- func (s *State) EnableBuiltin(b Builtin)
- func (s *State) EnableBuiltins(builtins ...Builtin)
- func (s *State) EnableExecutionBuiltins()
- func (s *State) EnableModule(m Module)
- func (s *State) EnableModules(modules ...Module)
- func (s *State) EnableReflectionBuiltins()
- func (s *State) EnabledBuiltins() []Builtin
- func (s *State) EnabledModules() []Module
- func (s *State) Execute(code *Code) (Value, error)
- func (s *State) ExecuteWithTimeout(code *Code, timeout time.Duration) (Value, error)
- func (s *State) GetGlobal(name string) Value
- func (s *State) GetGlobals() map[string]Value
- func (s *State) GetModuleAttr(moduleName, attrName string) Value
- func (s *State) IsBuiltinEnabled(b Builtin) bool
- func (s *State) IsModuleEnabled(m Module) bool
- func (s *State) Register(name string, fn GoFunc)
- func (s *State) RegisterBuiltin(name string, fn GoFunc)
- func (s *State) RegisterPythonModule(moduleName, source string) error
- func (s *State) Run(source string) (Value, error)
- func (s *State) RunWithContext(ctx context.Context, source string) (Value, error)
- func (s *State) RunWithFilename(source, filename string) (Value, error)
- func (s *State) RunWithTimeout(source string, timeout time.Duration) (Value, error)
- func (s *State) SetGlobal(name string, value Value)
- type StateOption
- func WithAllBuiltins() StateOption
- func WithAllModules() StateOption
- func WithBuiltin(b Builtin) StateOption
- func WithBuiltins(builtins ...Builtin) StateOption
- func WithExecutionBuiltins() StateOption
- func WithModule(m Module) StateOption
- func WithModules(modules ...Module) StateOption
- func WithReflectionBuiltins() StateOption
- type StringValue
- type TupleValue
- type UserDataValue
- type Value
- func AsList(v Value) ([]Value, bool)
- func AsTuple(v Value) ([]Value, bool)
- func Bool(v bool) Value
- func Complex(real, imag float64) Value
- func Dict(pairs ...any) Value
- func Eval(expr string) (Value, error)
- func Float(v float64) Value
- func FromGo(v any) Value
- func Int(v int64) Value
- func List(items ...Value) Value
- func Run(source string) (Value, error)
- func RunWithTimeout(source string, timeout time.Duration) (Value, error)
- func String(v string) Value
- func Tuple(items ...Value) Value
- func UserData(v any) Value
Constants ¶
This section is empty.
Variables ¶
var AllBuiltins = []Builtin{ BuiltinRepr, BuiltinDir, BuiltinGlobals, BuiltinLocals, BuiltinVars, BuiltinCompile, BuiltinExec, BuiltinEval, }
AllBuiltins contains all opt-in builtins.
var AllModules = []Module{ ModuleMath, ModuleRandom, ModuleString, ModuleSys, ModuleTime, ModuleRe, ModuleCollections, ModuleAsyncio, ModuleIO, ModuleJSON, ModuleOS, ModuleDatetime, ModuleTyping, ModuleCSV, ModuleItertools, ModuleFunctools, ModuleBase64, ModuleAbc, ModuleDataclasses, ModuleCopy, ModuleOperator, }
AllModules is a convenience slice containing all available modules.
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.
var ReflectionBuiltins = []Builtin{ BuiltinRepr, BuiltinDir, BuiltinGlobals, BuiltinLocals, BuiltinVars, }
ReflectionBuiltins contains all reflection-related builtins (repr, dir, globals, locals, vars). These are relatively safe introspection functions.
Functions ¶
func AsUserData ¶
AsUserData returns the userdata value or nil if not userdata
Types ¶
type BoolValue ¶
type BoolValue struct {
// contains filtered or unexported fields
}
BoolValue represents a Python bool
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.
type Code ¶
type Code struct {
// contains filtered or unexported fields
}
Code represents compiled Python bytecode.
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
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 IntValue ¶
type IntValue struct {
// contains filtered or unexported fields
}
IntValue represents a Python int
type ListValue ¶
type ListValue struct {
// contains filtered or unexported fields
}
ListValue represents a Python list
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 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 ¶
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 ¶
EnableBuiltin enables a specific opt-in builtin function. This can be called after state creation to add builtins.
func (*State) EnableBuiltins ¶
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 ¶
EnableModule enables a specific stdlib module. This can be called after state creation to add modules.
func (*State) EnableModules ¶
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 ¶
EnabledBuiltins returns a slice of all enabled builtins.
func (*State) EnabledModules ¶
EnabledModules returns a slice of all enabled modules.
func (*State) ExecuteWithTimeout ¶
ExecuteWithTimeout runs previously compiled code with a timeout.
func (*State) GetGlobals ¶
GetGlobals returns all global variables as a map.
func (*State) GetModuleAttr ¶
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 ¶
IsBuiltinEnabled returns true if the specified builtin is enabled.
func (*State) IsModuleEnabled ¶
IsModuleEnabled returns true if the specified module is enabled.
func (*State) Register ¶
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 ¶
RegisterBuiltin registers a Go function as a builtin.
func (*State) RegisterPythonModule ¶
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 ¶
Run compiles and executes Python source code. Returns the result of the last expression or nil.
func (*State) RunWithContext ¶
RunWithContext executes Python code with a context for cancellation.
func (*State) RunWithFilename ¶
RunWithFilename compiles and executes Python source code with a filename for error messages.
func (*State) RunWithTimeout ¶
RunWithTimeout executes Python code with a timeout.
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 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
func Eval ¶
Eval evaluates a Python expression and returns the result. Unlike Run, this expects an expression, not statements.
func Run ¶
Run is a convenience function that creates a temporary state, runs the code, and returns the result.
func RunWithTimeout ¶
RunWithTimeout runs Python code with a timeout.