rage

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Feb 21, 2026 License: MIT Imports: 9 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 ErrStopIteration = errors.New("StopIteration: ")

ErrStopIteration should be returned from Next callbacks to signal end of iteration.

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 AsBytes added in v0.2.0

func AsBytes(v Value) ([]byte, bool)

AsBytes returns the bytes value or nil if not bytes

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 AttributeError added in v0.2.0

func AttributeError(msg string) error

AttributeError returns an error that becomes a Python AttributeError.

func IndexError added in v0.2.0

func IndexError(msg string) error

IndexError returns an error that becomes a Python IndexError.

func IsBool

func IsBool(v Value) bool

IsBool returns true if the value is a bool

func IsBytes added in v0.2.0

func IsBytes(v Value) bool

IsBytes returns true if the value is bytes

func IsClass added in v0.2.0

func IsClass(v Value) bool

IsClass returns true if the value is a Python class (ClassValue)

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 IsObject added in v0.2.0

func IsObject(v Value) bool

IsObject returns true if the value is a Python instance (Object)

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

func KeyError added in v0.2.0

func KeyError(msg string) error

KeyError returns an error that becomes a Python KeyError.

func RuntimeError added in v0.2.0

func RuntimeError(msg string) error

RuntimeError returns an error that becomes a Python RuntimeError.

func TypeError added in v0.2.0

func TypeError(msg string) error

TypeError returns an error that becomes a Python TypeError.

func ValueError added in v0.2.0

func ValueError(msg string) error

ValueError returns an error that becomes a Python ValueError.

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 BytesValue added in v0.2.0

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

BytesValue represents a Python bytes

func (BytesValue) Bytes added in v0.2.0

func (v BytesValue) Bytes() []byte

func (BytesValue) GoValue added in v0.2.0

func (v BytesValue) GoValue() any

func (BytesValue) String added in v0.2.0

func (v BytesValue) String() string

func (BytesValue) Type added in v0.2.0

func (v BytesValue) Type() string

type ClassBuilder added in v0.2.0

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

ClassBuilder provides a fluent API for building Python classes from Go.

func NewClass added in v0.2.0

func NewClass(name string) *ClassBuilder

NewClass starts building a new Python class with the given name.

func (*ClassBuilder) AIter added in v0.2.0

func (b *ClassBuilder) AIter(fn func(s *State, self Object) (Value, error)) *ClassBuilder

AIter sets __aiter__. Called by async for to get an async iterator.

func (*ClassBuilder) ANext added in v0.2.0

func (b *ClassBuilder) ANext(fn func(s *State, self Object) (Value, error)) *ClassBuilder

ANext sets __anext__. Called by async for to get the next value.

func (*ClassBuilder) Abs added in v0.2.0

func (b *ClassBuilder) Abs(fn func(s *State, self Object) (Value, error)) *ClassBuilder

Abs sets __abs__ (abs() builtin).

func (*ClassBuilder) Add added in v0.2.0

func (b *ClassBuilder) Add(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

Add sets __add__.

func (*ClassBuilder) And added in v0.2.0

func (b *ClassBuilder) And(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

And sets __and__.

func (*ClassBuilder) Attr added in v0.2.0

func (b *ClassBuilder) Attr(name string, val Value) *ClassBuilder

Attr sets a class-level attribute (installed into the class dict).

func (*ClassBuilder) Await added in v0.2.0

func (b *ClassBuilder) Await(fn func(s *State, self Object) (Value, error)) *ClassBuilder

Await sets __await__. Called by the await expression.

func (*ClassBuilder) Base added in v0.2.0

func (b *ClassBuilder) Base(base ClassValue) *ClassBuilder

Base sets a single base class. If not called, defaults to object.

func (*ClassBuilder) Bases added in v0.2.0

func (b *ClassBuilder) Bases(bases ...ClassValue) *ClassBuilder

Bases sets multiple base classes for multiple inheritance.

func (*ClassBuilder) Bool added in v0.2.0

func (b *ClassBuilder) Bool(fn func(s *State, self Object) (bool, error)) *ClassBuilder

Bool sets the __bool__ method.

func (*ClassBuilder) Build added in v0.2.0

func (b *ClassBuilder) Build(s *State) ClassValue

Build creates the Python class and registers it in the given State. Returns a ClassValue that can be passed to State.SetGlobal.

func (*ClassBuilder) BytesConv added in v0.2.0

func (b *ClassBuilder) BytesConv(fn func(s *State, self Object) ([]byte, error)) *ClassBuilder

BytesConv sets __bytes__ (bytes() builtin).

func (*ClassBuilder) Call added in v0.2.0

func (b *ClassBuilder) Call(fn func(s *State, self Object, args ...Value) (Value, error)) *ClassBuilder

Call sets the __call__ method, making instances callable.

func (*ClassBuilder) CallKw added in v0.2.0

func (b *ClassBuilder) CallKw(fn func(s *State, self Object, args []Value, kwargs map[string]Value) (Value, error)) *ClassBuilder

CallKw sets the __call__ method with keyword argument support.

func (*ClassBuilder) ClassGetItem added in v0.2.0

func (b *ClassBuilder) ClassGetItem(fn func(s *State, cls ClassValue, key Value) (Value, error)) *ClassBuilder

ClassGetItem sets __class_getitem__. Called for MyClass[key] syntax (e.g. generics). Installed as a class method.

func (*ClassBuilder) ClassMethod added in v0.2.0

func (b *ClassBuilder) ClassMethod(name string, fn func(s *State, cls ClassValue, args ...Value) (Value, error)) *ClassBuilder

ClassMethod adds a class method. The first argument to fn is the class, not an instance.

func (*ClassBuilder) ClassMethodKw added in v0.2.0

func (b *ClassBuilder) ClassMethodKw(name string, fn func(s *State, cls ClassValue, args []Value, kwargs map[string]Value) (Value, error)) *ClassBuilder

ClassMethodKw adds a class method with keyword argument support.

func (*ClassBuilder) ComplexConv added in v0.2.0

func (b *ClassBuilder) ComplexConv(fn func(s *State, self Object) (complex128, error)) *ClassBuilder

ComplexConv sets __complex__ (complex() builtin).

func (*ClassBuilder) Contains added in v0.2.0

func (b *ClassBuilder) Contains(fn func(s *State, self Object, item Value) (bool, error)) *ClassBuilder

Contains sets the __contains__ method.

func (*ClassBuilder) Del added in v0.2.0

func (b *ClassBuilder) Del(fn func(s *State, self Object) error) *ClassBuilder

Del sets __del__ (destructor, called on garbage collection, best-effort).

func (*ClassBuilder) DelAttr added in v0.2.0

func (b *ClassBuilder) DelAttr(fn func(s *State, self Object, name string) error) *ClassBuilder

DelAttr sets __delattr__. Called on attribute deletion.

func (*ClassBuilder) DelItem added in v0.2.0

func (b *ClassBuilder) DelItem(fn func(s *State, self Object, key Value) error) *ClassBuilder

DelItem sets the __delitem__ method.

func (*ClassBuilder) DescDelete added in v0.2.0

func (b *ClassBuilder) DescDelete(fn func(s *State, self Object, instance Value) error) *ClassBuilder

DescDelete sets __delete__ for the descriptor protocol.

func (*ClassBuilder) DescGet added in v0.2.0

func (b *ClassBuilder) DescGet(fn func(s *State, self Object, instance, owner Value) (Value, error)) *ClassBuilder

DescGet sets __get__ for the descriptor protocol.

func (*ClassBuilder) DescSet added in v0.2.0

func (b *ClassBuilder) DescSet(fn func(s *State, self Object, instance, val Value) error) *ClassBuilder

DescSet sets __set__ for the descriptor protocol.

func (*ClassBuilder) Dir added in v0.2.0

func (b *ClassBuilder) Dir(fn func(s *State, self Object) (Value, error)) *ClassBuilder

Dir sets __dir__. Called by the dir() builtin.

func (*ClassBuilder) Dunder added in v0.2.0

func (b *ClassBuilder) Dunder(name string, fn func(s *State, self Object, args ...Value) (Value, error)) *ClassBuilder

Dunder adds an arbitrary dunder method.

func (*ClassBuilder) Enter added in v0.2.0

func (b *ClassBuilder) Enter(fn func(s *State, self Object) (Value, error)) *ClassBuilder

Enter sets the __enter__ method for context managers.

func (*ClassBuilder) Eq added in v0.2.0

func (b *ClassBuilder) Eq(fn func(s *State, self Object, other Value) (bool, error)) *ClassBuilder

Eq sets the __eq__ method.

func (*ClassBuilder) Exit added in v0.2.0

func (b *ClassBuilder) Exit(fn func(s *State, self Object, excType, excVal, excTb Value) (bool, error)) *ClassBuilder

Exit sets the __exit__ method for context managers. Return true to suppress the exception, false to propagate it. excType, excVal, and excTb are None when no exception occurred.

func (*ClassBuilder) FloatConv added in v0.2.0

func (b *ClassBuilder) FloatConv(fn func(s *State, self Object) (float64, error)) *ClassBuilder

FloatConv sets __float__ (float() builtin).

func (*ClassBuilder) FloorDiv added in v0.2.0

func (b *ClassBuilder) FloorDiv(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

FloorDiv sets __floordiv__.

func (*ClassBuilder) Format added in v0.2.0

func (b *ClassBuilder) Format(fn func(s *State, self Object, spec string) (string, error)) *ClassBuilder

Format sets __format__ (format() builtin and f-strings).

func (*ClassBuilder) Ge added in v0.2.0

func (b *ClassBuilder) Ge(fn func(s *State, self Object, other Value) (bool, error)) *ClassBuilder

Ge sets the __ge__ method.

func (*ClassBuilder) GetAttr added in v0.2.0

func (b *ClassBuilder) GetAttr(fn func(s *State, self Object, name string) (Value, error)) *ClassBuilder

GetAttr sets __getattr__. Called when normal attribute lookup fails.

func (*ClassBuilder) GetAttribute added in v0.2.0

func (b *ClassBuilder) GetAttribute(fn func(s *State, self Object, name string) (Value, error)) *ClassBuilder

GetAttribute sets __getattribute__. Called on every attribute access (before __getattr__).

func (*ClassBuilder) GetItem added in v0.2.0

func (b *ClassBuilder) GetItem(fn func(s *State, self Object, key Value) (Value, error)) *ClassBuilder

GetItem sets the __getitem__ method.

func (*ClassBuilder) Gt added in v0.2.0

func (b *ClassBuilder) Gt(fn func(s *State, self Object, other Value) (bool, error)) *ClassBuilder

Gt sets the __gt__ method.

func (*ClassBuilder) Hash added in v0.2.0

func (b *ClassBuilder) Hash(fn func(s *State, self Object) (int64, error)) *ClassBuilder

Hash sets the __hash__ method.

func (*ClassBuilder) IAdd added in v0.2.0

func (b *ClassBuilder) IAdd(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

IAdd sets __iadd__.

func (*ClassBuilder) IAnd added in v0.2.0

func (b *ClassBuilder) IAnd(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

IAnd sets __iand__.

func (*ClassBuilder) IFloorDiv added in v0.2.0

func (b *ClassBuilder) IFloorDiv(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

IFloorDiv sets __ifloordiv__.

func (*ClassBuilder) ILShift added in v0.2.0

func (b *ClassBuilder) ILShift(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

ILShift sets __ilshift__.

func (*ClassBuilder) IMatMul added in v0.2.0

func (b *ClassBuilder) IMatMul(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

IMatMul sets __imatmul__.

func (*ClassBuilder) IMod added in v0.2.0

func (b *ClassBuilder) IMod(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

IMod sets __imod__.

func (*ClassBuilder) IMul added in v0.2.0

func (b *ClassBuilder) IMul(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

IMul sets __imul__.

func (*ClassBuilder) IOr added in v0.2.0

func (b *ClassBuilder) IOr(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

IOr sets __ior__.

func (*ClassBuilder) IPow added in v0.2.0

func (b *ClassBuilder) IPow(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

IPow sets __ipow__.

func (*ClassBuilder) IRShift added in v0.2.0

func (b *ClassBuilder) IRShift(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

IRShift sets __irshift__.

func (*ClassBuilder) ISub added in v0.2.0

func (b *ClassBuilder) ISub(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

ISub sets __isub__.

func (*ClassBuilder) ITrueDiv added in v0.2.0

func (b *ClassBuilder) ITrueDiv(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

ITrueDiv sets __itruediv__.

func (*ClassBuilder) IXor added in v0.2.0

func (b *ClassBuilder) IXor(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

IXor sets __ixor__.

func (*ClassBuilder) Index added in v0.2.0

func (b *ClassBuilder) Index(fn func(s *State, self Object) (int64, error)) *ClassBuilder

Index sets __index__ (used for slicing, indexing, and operator.index()).

func (*ClassBuilder) Init added in v0.2.0

func (b *ClassBuilder) Init(fn func(s *State, self Object, args ...Value) error) *ClassBuilder

Init sets the __init__ method.

func (*ClassBuilder) InitKw added in v0.2.0

func (b *ClassBuilder) InitKw(fn func(s *State, self Object, args []Value, kwargs map[string]Value) error) *ClassBuilder

InitKw sets the __init__ method with keyword argument support.

func (*ClassBuilder) InitSubclass added in v0.2.0

func (b *ClassBuilder) InitSubclass(fn func(s *State, cls ClassValue, kwargs map[string]Value) error) *ClassBuilder

InitSubclass sets __init_subclass__. Called when a class is subclassed. Installed as a class method. kwargs contains keyword arguments from the class statement.

func (*ClassBuilder) IntConv added in v0.2.0

func (b *ClassBuilder) IntConv(fn func(s *State, self Object) (int64, error)) *ClassBuilder

IntConv sets __int__ (int() builtin).

func (*ClassBuilder) Invert added in v0.2.0

func (b *ClassBuilder) Invert(fn func(s *State, self Object) (Value, error)) *ClassBuilder

Invert sets __invert__ (unary ~).

func (*ClassBuilder) Iter added in v0.2.0

func (b *ClassBuilder) Iter(fn func(s *State, self Object) (Value, error)) *ClassBuilder

Iter sets the __iter__ method. Return self for objects that are their own iterator.

func (*ClassBuilder) LShift added in v0.2.0

func (b *ClassBuilder) LShift(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

LShift sets __lshift__.

func (*ClassBuilder) Le added in v0.2.0

func (b *ClassBuilder) Le(fn func(s *State, self Object, other Value) (bool, error)) *ClassBuilder

Le sets the __le__ method.

func (*ClassBuilder) Len added in v0.2.0

func (b *ClassBuilder) Len(fn func(s *State, self Object) (int64, error)) *ClassBuilder

Len sets the __len__ method.

func (*ClassBuilder) Lt added in v0.2.0

func (b *ClassBuilder) Lt(fn func(s *State, self Object, other Value) (bool, error)) *ClassBuilder

Lt sets the __lt__ method.

func (*ClassBuilder) MatMul added in v0.2.0

func (b *ClassBuilder) MatMul(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

MatMul sets __matmul__.

func (*ClassBuilder) Method added in v0.2.0

func (b *ClassBuilder) Method(name string, fn func(s *State, self Object, args ...Value) (Value, error)) *ClassBuilder

Method adds a regular instance method.

func (*ClassBuilder) MethodKw added in v0.2.0

func (b *ClassBuilder) MethodKw(name string, fn func(s *State, self Object, args []Value, kwargs map[string]Value) (Value, error)) *ClassBuilder

MethodKw adds an instance method with keyword argument support.

func (*ClassBuilder) Missing added in v0.2.0

func (b *ClassBuilder) Missing(fn func(s *State, self Object, key Value) (Value, error)) *ClassBuilder

Missing sets __missing__. Called by dict subclasses when a key is not found.

func (*ClassBuilder) Mod added in v0.2.0

func (b *ClassBuilder) Mod(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

Mod sets __mod__.

func (*ClassBuilder) Mul added in v0.2.0

func (b *ClassBuilder) Mul(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

Mul sets __mul__.

func (*ClassBuilder) Ne added in v0.2.0

func (b *ClassBuilder) Ne(fn func(s *State, self Object, other Value) (bool, error)) *ClassBuilder

Ne sets the __ne__ method.

func (*ClassBuilder) Neg added in v0.2.0

func (b *ClassBuilder) Neg(fn func(s *State, self Object) (Value, error)) *ClassBuilder

Neg sets __neg__ (unary -).

func (*ClassBuilder) New added in v0.2.0

func (b *ClassBuilder) New(fn func(s *State, cls ClassValue, args ...Value) (Object, error)) *ClassBuilder

New sets a custom __new__ method. The function receives the class and args, and should return a new Object (typically via cls.NewInstance()).

func (*ClassBuilder) NewKw added in v0.2.0

func (b *ClassBuilder) NewKw(fn func(s *State, cls ClassValue, args []Value, kwargs map[string]Value) (Object, error)) *ClassBuilder

NewKw sets a custom __new__ method with keyword argument support.

func (*ClassBuilder) Next added in v0.2.0

func (b *ClassBuilder) Next(fn func(s *State, self Object) (Value, error)) *ClassBuilder

Next sets the __next__ method. Return ErrStopIteration to signal end of iteration.

func (*ClassBuilder) Or added in v0.2.0

func (b *ClassBuilder) Or(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

Or sets __or__.

func (*ClassBuilder) Pos added in v0.2.0

func (b *ClassBuilder) Pos(fn func(s *State, self Object) (Value, error)) *ClassBuilder

Pos sets __pos__ (unary +).

func (*ClassBuilder) Pow added in v0.2.0

func (b *ClassBuilder) Pow(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

Pow sets __pow__.

func (*ClassBuilder) Property added in v0.2.0

func (b *ClassBuilder) Property(name string, getter func(s *State, self Object) (Value, error)) *ClassBuilder

Property adds a read-only property.

func (*ClassBuilder) PropertyWithSetter added in v0.2.0

func (b *ClassBuilder) PropertyWithSetter(name string, getter func(s *State, self Object) (Value, error), setter func(s *State, self Object, val Value) error) *ClassBuilder

PropertyWithSetter adds a read-write property.

func (*ClassBuilder) RAdd added in v0.2.0

func (b *ClassBuilder) RAdd(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

RAdd sets __radd__.

func (*ClassBuilder) RAnd added in v0.2.0

func (b *ClassBuilder) RAnd(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

RAnd sets __rand__.

func (*ClassBuilder) RFloorDiv added in v0.2.0

func (b *ClassBuilder) RFloorDiv(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

RFloorDiv sets __rfloordiv__.

func (*ClassBuilder) RLShift added in v0.2.0

func (b *ClassBuilder) RLShift(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

RLShift sets __rlshift__.

func (*ClassBuilder) RMatMul added in v0.2.0

func (b *ClassBuilder) RMatMul(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

RMatMul sets __rmatmul__.

func (*ClassBuilder) RMod added in v0.2.0

func (b *ClassBuilder) RMod(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

RMod sets __rmod__.

func (*ClassBuilder) RMul added in v0.2.0

func (b *ClassBuilder) RMul(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

RMul sets __rmul__.

func (*ClassBuilder) ROr added in v0.2.0

func (b *ClassBuilder) ROr(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

ROr sets __ror__.

func (*ClassBuilder) RPow added in v0.2.0

func (b *ClassBuilder) RPow(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

RPow sets __rpow__.

func (*ClassBuilder) RRShift added in v0.2.0

func (b *ClassBuilder) RRShift(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

RRShift sets __rrshift__.

func (*ClassBuilder) RShift added in v0.2.0

func (b *ClassBuilder) RShift(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

RShift sets __rshift__.

func (*ClassBuilder) RSub added in v0.2.0

func (b *ClassBuilder) RSub(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

RSub sets __rsub__.

func (*ClassBuilder) RTrueDiv added in v0.2.0

func (b *ClassBuilder) RTrueDiv(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

RTrueDiv sets __rtruediv__.

func (*ClassBuilder) RXor added in v0.2.0

func (b *ClassBuilder) RXor(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

RXor sets __rxor__.

func (*ClassBuilder) Repr added in v0.2.0

func (b *ClassBuilder) Repr(fn func(s *State, self Object) (string, error)) *ClassBuilder

Repr sets the __repr__ method.

func (*ClassBuilder) Reversed added in v0.2.0

func (b *ClassBuilder) Reversed(fn func(s *State, self Object) (Value, error)) *ClassBuilder

Reversed sets __reversed__. Called by the reversed() builtin.

func (*ClassBuilder) Round added in v0.2.0

func (b *ClassBuilder) Round(fn func(s *State, self Object, ndigits Value) (Value, error)) *ClassBuilder

Round sets __round__. Called by the round() builtin. ndigits is None when round() is called with one argument.

func (*ClassBuilder) SetAttr added in v0.2.0

func (b *ClassBuilder) SetAttr(fn func(s *State, self Object, name string, val Value) error) *ClassBuilder

SetAttr sets __setattr__. Called on all attribute assignments.

func (*ClassBuilder) SetItem added in v0.2.0

func (b *ClassBuilder) SetItem(fn func(s *State, self Object, key, val Value) error) *ClassBuilder

SetItem sets the __setitem__ method.

func (*ClassBuilder) SetName added in v0.2.0

func (b *ClassBuilder) SetName(fn func(s *State, self Object, owner Value, name string) error) *ClassBuilder

SetName sets __set_name__. Called when a descriptor is assigned to a class attribute.

func (*ClassBuilder) StaticMethod added in v0.2.0

func (b *ClassBuilder) StaticMethod(name string, fn func(s *State, args ...Value) (Value, error)) *ClassBuilder

StaticMethod adds a static method. No self or cls is passed.

func (*ClassBuilder) StaticMethodKw added in v0.2.0

func (b *ClassBuilder) StaticMethodKw(name string, fn func(s *State, args []Value, kwargs map[string]Value) (Value, error)) *ClassBuilder

StaticMethodKw adds a static method with keyword argument support.

func (*ClassBuilder) Str added in v0.2.0

func (b *ClassBuilder) Str(fn func(s *State, self Object) (string, error)) *ClassBuilder

Str sets the __str__ method.

func (*ClassBuilder) Sub added in v0.2.0

func (b *ClassBuilder) Sub(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

Sub sets __sub__.

func (*ClassBuilder) TrueDiv added in v0.2.0

func (b *ClassBuilder) TrueDiv(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

TrueDiv sets __truediv__.

func (*ClassBuilder) Xor added in v0.2.0

func (b *ClassBuilder) Xor(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder

Xor sets __xor__.

type ClassValue added in v0.2.0

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

ClassValue wraps a *runtime.PyClass, implementing rage.Value.

func AsClass added in v0.2.0

func AsClass(v Value) (ClassValue, bool)

AsClass returns the ClassValue or zero value if not a ClassValue

func (ClassValue) GoValue added in v0.2.0

func (c ClassValue) GoValue() any

GoValue returns the underlying *runtime.PyClass.

func (ClassValue) Name added in v0.2.0

func (c ClassValue) Name() string

Name returns the class name.

func (ClassValue) NewInstance added in v0.2.0

func (c ClassValue) NewInstance() Object

NewInstance creates a new instance of this class without calling __init__. Useful for Go code that wants to set up attributes manually.

func (ClassValue) String added in v0.2.0

func (c ClassValue) String() string

String returns the class string representation.

func (ClassValue) Type added in v0.2.0

func (c ClassValue) Type() string

Type returns "type".

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
	ModuleEnum
)

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 Object added in v0.2.0

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

Object wraps a Python instance, providing Go methods to read and write attributes on self.

func AsObject added in v0.2.0

func AsObject(v Value) (Object, bool)

AsObject returns the Object or zero value if not an Object

func (Object) Class added in v0.2.0

func (o Object) Class() ClassValue

Class returns the ClassValue of this instance.

func (Object) ClassName added in v0.2.0

func (o Object) ClassName() string

ClassName returns the name of the instance's class.

func (Object) Delete added in v0.2.0

func (o Object) Delete(name string)

Delete removes an attribute from the instance.

func (Object) Get added in v0.2.0

func (o Object) Get(name string) Value

Get returns the value of an attribute on the instance.

func (Object) GoValue added in v0.2.0

func (o Object) GoValue() any

GoValue returns the underlying *runtime.PyInstance.

func (Object) Has added in v0.2.0

func (o Object) Has(name string) bool

Has returns true if the instance has the named attribute.

func (Object) Set added in v0.2.0

func (o Object) Set(name string, val Value)

Set sets an attribute on the instance.

func (Object) String added in v0.2.0

func (o Object) String() string

String returns a string representation of this object.

func (Object) Type added in v0.2.0

func (o Object) Type() string

Type returns the Python type name of this object.

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) AllocatedBytes added in v0.3.0

func (s *State) AllocatedBytes() int64

AllocatedBytes returns the approximate number of bytes currently tracked by the VM.

func (*State) Call added in v0.2.0

func (s *State) Call(callable Value, args ...Value) (Value, error)

Call invokes a callable Python value (function, class, etc.) with the given arguments. This allows Go code to call Python functions or instantiate classes directly.

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.

func (*State) SetMaxCollectionSize added in v0.3.0

func (s *State) SetMaxCollectionSize(n int64)

SetMaxCollectionSize sets the maximum number of elements in a single collection. 0 means unlimited.

func (*State) SetMaxMemoryBytes added in v0.3.0

func (s *State) SetMaxMemoryBytes(n int64)

SetMaxMemoryBytes sets the approximate memory limit in bytes. 0 means unlimited.

func (*State) SetMaxRecursionDepth added in v0.3.0

func (s *State) SetMaxRecursionDepth(n int64)

SetMaxRecursionDepth sets the maximum call stack depth. 0 means unlimited.

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 WithMaxCollectionSize added in v0.3.0

func WithMaxCollectionSize(n int64) StateOption

WithMaxCollectionSize sets the maximum number of elements in a single collection. 0 means unlimited.

func WithMaxMemoryBytes added in v0.3.0

func WithMaxMemoryBytes(n int64) StateOption

WithMaxMemoryBytes sets the approximate memory limit in bytes. 0 means unlimited.

func WithMaxRecursionDepth added in v0.3.0

func WithMaxRecursionDepth(n int64) StateOption

WithMaxRecursionDepth sets the maximum call stack depth. 0 means unlimited.

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 Bytes added in v0.2.0

func Bytes(v []byte) Value

Bytes creates a Python bytes 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