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 AsBytes(v Value) ([]byte, 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 AttributeError(msg string) error
- func IndexError(msg string) error
- func IsBool(v Value) bool
- func IsBytes(v Value) bool
- func IsClass(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 IsObject(v Value) bool
- func IsString(v Value) bool
- func IsTuple(v Value) bool
- func IsUserData(v Value) bool
- func KeyError(msg string) error
- func RuntimeError(msg string) error
- func TypeError(msg string) error
- func ValueError(msg string) error
- type BoolValue
- type Builtin
- type BytesValue
- type ClassBuilder
- func (b *ClassBuilder) AIter(fn func(s *State, self Object) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) ANext(fn func(s *State, self Object) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Abs(fn func(s *State, self Object) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Add(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) And(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Attr(name string, val Value) *ClassBuilder
- func (b *ClassBuilder) Await(fn func(s *State, self Object) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Base(base ClassValue) *ClassBuilder
- func (b *ClassBuilder) Bases(bases ...ClassValue) *ClassBuilder
- func (b *ClassBuilder) Bool(fn func(s *State, self Object) (bool, error)) *ClassBuilder
- func (b *ClassBuilder) Build(s *State) ClassValue
- func (b *ClassBuilder) BytesConv(fn func(s *State, self Object) ([]byte, error)) *ClassBuilder
- func (b *ClassBuilder) Call(fn func(s *State, self Object, args ...Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) CallKw(...) *ClassBuilder
- func (b *ClassBuilder) ClassGetItem(fn func(s *State, cls ClassValue, key Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) ClassMethod(name string, fn func(s *State, cls ClassValue, args ...Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) ClassMethodKw(name string, ...) *ClassBuilder
- func (b *ClassBuilder) ComplexConv(fn func(s *State, self Object) (complex128, error)) *ClassBuilder
- func (b *ClassBuilder) Contains(fn func(s *State, self Object, item Value) (bool, error)) *ClassBuilder
- func (b *ClassBuilder) Del(fn func(s *State, self Object) error) *ClassBuilder
- func (b *ClassBuilder) DelAttr(fn func(s *State, self Object, name string) error) *ClassBuilder
- func (b *ClassBuilder) DelItem(fn func(s *State, self Object, key Value) error) *ClassBuilder
- func (b *ClassBuilder) DescDelete(fn func(s *State, self Object, instance Value) error) *ClassBuilder
- func (b *ClassBuilder) DescGet(fn func(s *State, self Object, instance, owner Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) DescSet(fn func(s *State, self Object, instance, val Value) error) *ClassBuilder
- func (b *ClassBuilder) Dir(fn func(s *State, self Object) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Dunder(name string, fn func(s *State, self Object, args ...Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Enter(fn func(s *State, self Object) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Eq(fn func(s *State, self Object, other Value) (bool, error)) *ClassBuilder
- func (b *ClassBuilder) Exit(fn func(s *State, self Object, excType, excVal, excTb Value) (bool, error)) *ClassBuilder
- func (b *ClassBuilder) FloatConv(fn func(s *State, self Object) (float64, error)) *ClassBuilder
- func (b *ClassBuilder) FloorDiv(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Format(fn func(s *State, self Object, spec string) (string, error)) *ClassBuilder
- func (b *ClassBuilder) Ge(fn func(s *State, self Object, other Value) (bool, error)) *ClassBuilder
- func (b *ClassBuilder) GetAttr(fn func(s *State, self Object, name string) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) GetAttribute(fn func(s *State, self Object, name string) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) GetItem(fn func(s *State, self Object, key Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Gt(fn func(s *State, self Object, other Value) (bool, error)) *ClassBuilder
- func (b *ClassBuilder) Hash(fn func(s *State, self Object) (int64, error)) *ClassBuilder
- func (b *ClassBuilder) IAdd(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) IAnd(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) IFloorDiv(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) ILShift(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) IMatMul(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) IMod(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) IMul(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) IOr(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) IPow(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) IRShift(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) ISub(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) ITrueDiv(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) IXor(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Index(fn func(s *State, self Object) (int64, error)) *ClassBuilder
- func (b *ClassBuilder) Init(fn func(s *State, self Object, args ...Value) error) *ClassBuilder
- func (b *ClassBuilder) InitKw(fn func(s *State, self Object, args []Value, kwargs map[string]Value) error) *ClassBuilder
- func (b *ClassBuilder) InitSubclass(fn func(s *State, cls ClassValue, kwargs map[string]Value) error) *ClassBuilder
- func (b *ClassBuilder) IntConv(fn func(s *State, self Object) (int64, error)) *ClassBuilder
- func (b *ClassBuilder) Invert(fn func(s *State, self Object) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Iter(fn func(s *State, self Object) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) LShift(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Le(fn func(s *State, self Object, other Value) (bool, error)) *ClassBuilder
- func (b *ClassBuilder) Len(fn func(s *State, self Object) (int64, error)) *ClassBuilder
- func (b *ClassBuilder) Lt(fn func(s *State, self Object, other Value) (bool, error)) *ClassBuilder
- func (b *ClassBuilder) MatMul(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Method(name string, fn func(s *State, self Object, args ...Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) MethodKw(name string, ...) *ClassBuilder
- func (b *ClassBuilder) Missing(fn func(s *State, self Object, key Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Mod(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Mul(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Ne(fn func(s *State, self Object, other Value) (bool, error)) *ClassBuilder
- func (b *ClassBuilder) Neg(fn func(s *State, self Object) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) New(fn func(s *State, cls ClassValue, args ...Value) (Object, error)) *ClassBuilder
- func (b *ClassBuilder) NewKw(...) *ClassBuilder
- func (b *ClassBuilder) Next(fn func(s *State, self Object) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Or(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Pos(fn func(s *State, self Object) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Pow(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Property(name string, getter func(s *State, self Object) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) PropertyWithSetter(name string, getter func(s *State, self Object) (Value, error), ...) *ClassBuilder
- func (b *ClassBuilder) RAdd(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) RAnd(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) RFloorDiv(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) RLShift(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) RMatMul(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) RMod(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) RMul(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) ROr(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) RPow(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) RRShift(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) RShift(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) RSub(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) RTrueDiv(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) RXor(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Repr(fn func(s *State, self Object) (string, error)) *ClassBuilder
- func (b *ClassBuilder) Reversed(fn func(s *State, self Object) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Round(fn func(s *State, self Object, ndigits Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) SetAttr(fn func(s *State, self Object, name string, val Value) error) *ClassBuilder
- func (b *ClassBuilder) SetItem(fn func(s *State, self Object, key, val Value) error) *ClassBuilder
- func (b *ClassBuilder) SetName(fn func(s *State, self Object, owner Value, name string) error) *ClassBuilder
- func (b *ClassBuilder) StaticMethod(name string, fn func(s *State, args ...Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) StaticMethodKw(name string, ...) *ClassBuilder
- func (b *ClassBuilder) Str(fn func(s *State, self Object) (string, error)) *ClassBuilder
- func (b *ClassBuilder) Sub(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) TrueDiv(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- func (b *ClassBuilder) Xor(fn func(s *State, self Object, other Value) (Value, error)) *ClassBuilder
- type ClassValue
- type Code
- type CompileErrors
- type ComplexValue
- type DictValue
- type FloatValue
- type FunctionValue
- type GoFunc
- type IntValue
- type ListValue
- type Module
- type NoneValue
- type Object
- func (o Object) Class() ClassValue
- func (o Object) ClassName() string
- func (o Object) Delete(name string)
- func (o Object) Get(name string) Value
- func (o Object) GoValue() any
- func (o Object) Has(name string) bool
- func (o Object) Set(name string, val Value)
- func (o Object) String() string
- func (o Object) Type() string
- type State
- func (s *State) AllocatedBytes() int64
- func (s *State) Call(callable Value, args ...Value) (Value, error)
- 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)
- func (s *State) SetMaxCollectionSize(n int64)
- func (s *State) SetMaxMemoryBytes(n int64)
- func (s *State) SetMaxRecursionDepth(n int64)
- type StateOption
- func WithAllBuiltins() StateOption
- func WithAllModules() StateOption
- func WithBuiltin(b Builtin) StateOption
- func WithBuiltins(builtins ...Builtin) StateOption
- func WithExecutionBuiltins() StateOption
- func WithMaxCollectionSize(n int64) StateOption
- func WithMaxMemoryBytes(n int64) StateOption
- func WithMaxRecursionDepth(n int64) 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 Bytes(v []byte) 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, ModuleEnum, }
AllModules is a convenience slice containing all available modules.
var ErrStopIteration = errors.New("StopIteration: ")
ErrStopIteration should be returned from Next callbacks to signal end of iteration.
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
func AttributeError ¶ added in v0.2.0
AttributeError returns an error that becomes a Python AttributeError.
func IndexError ¶ added in v0.2.0
IndexError returns an error that becomes a Python IndexError.
func RuntimeError ¶ added in v0.2.0
RuntimeError returns an error that becomes a Python RuntimeError.
func ValueError ¶ added in v0.2.0
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
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 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.
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 ModuleEnum )
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 (Object) Class ¶ added in v0.2.0
func (o Object) Class() ClassValue
Class returns the ClassValue of this instance.
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
AllocatedBytes returns the approximate number of bytes currently tracked by the VM.
func (*State) Call ¶ added in v0.2.0
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 ¶
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.
func (*State) SetMaxCollectionSize ¶ added in v0.3.0
SetMaxCollectionSize sets the maximum number of elements in a single collection. 0 means unlimited.
func (*State) SetMaxMemoryBytes ¶ added in v0.3.0
SetMaxMemoryBytes sets the approximate memory limit in bytes. 0 means unlimited.
func (*State) SetMaxRecursionDepth ¶ added in v0.3.0
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 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
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.