runtime

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: 16 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	True  = &PyBool{Value: true}
	False = &PyBool{Value: false}
)

True and False are singleton boolean values

View Source
var CompileFunc func(source, filename, mode string) (*CodeObject, error)

CompileFunc is set by the rage package to provide compilation capability for exec/eval/compile builtins. This avoids import cycles between runtime and compiler packages.

View Source
var None = &PyNone{}

None is the singleton None value

View Source
var NotImplemented = &PyNotImplementedType{}

NotImplemented is the singleton NotImplemented value

View Source
var OpcodeNames = map[Opcode]string{}/* 180 elements not displayed */

OpcodeNames maps opcodes to their string names for debugging

Functions

func BuiltinCompile

func BuiltinCompile(vm *VM) int

BuiltinCompile implements compile(source, filename, mode)

func BuiltinDir

func BuiltinDir(vm *VM) int

BuiltinDir implements dir([obj])

func BuiltinEval

func BuiltinEval(vm *VM) int

BuiltinEval implements eval(expression, globals=None, locals=None)

func BuiltinExec

func BuiltinExec(vm *VM) int

BuiltinExec implements exec(code, globals=None, locals=None)

func BuiltinGlobals

func BuiltinGlobals(vm *VM) int

BuiltinGlobals implements globals()

func BuiltinLocals

func BuiltinLocals(vm *VM) int

BuiltinLocals implements locals()

func BuiltinRepr

func BuiltinRepr(vm *VM) int

BuiltinRepr implements repr(obj)

func BuiltinVars

func BuiltinVars(vm *VM) int

BuiltinVars implements vars([obj])

func GetPendingBuiltins

func GetPendingBuiltins() map[string]GoFunction

GetPendingBuiltins returns all pending builtins (called by NewVM)

func IsBool

func IsBool(v Value) bool

IsBool checks if a value is a bool

func IsCallable

func IsCallable(v Value) bool

IsCallable checks if a value is callable

func IsDict

func IsDict(v Value) bool

IsDict checks if a value is a dict

func IsFloat

func IsFloat(v Value) bool

IsFloat checks if a value is a float

func IsInt

func IsInt(v Value) bool

IsInt checks if a value is an int

func IsList

func IsList(v Value) bool

IsList checks if a value is a list

func IsNone

func IsNone(v Value) bool

IsNone checks if a value is None

func IsString

func IsString(v Value) bool

IsString checks if a value is a string

func IsTrue

func IsTrue(v Value) bool

IsTrue returns whether a Python value is truthy (without needing a VM reference). This handles common cases; for instances with __bool__/__len__, use vm.Truthy instead.

func IsTuple

func IsTuple(v Value) bool

IsTuple checks if a value is a tuple

func IsUserData

func IsUserData(v Value) bool

IsUserData checks if a value is userdata

func RegisterModule

func RegisterModule(name string, loader ModuleLoader)

RegisterModule registers a module loader with the given name The loader will be called when the module is first imported

func RegisterPendingBuiltin

func RegisterPendingBuiltin(name string, fn GoFunction)

RegisterPendingBuiltin registers a builtin to be added to new VMs. Use this from stdlib modules that need to add builtin functions.

func RegisterTypeMetatable

func RegisterTypeMetatable(typeName string, mt *TypeMetatable)

RegisterTypeMetatable registers a type metatable globally (without VM instance)

func ResetModules

func ResetModules()

ResetModules clears the loaded modules cache and related registries. This should be called before initializing a new State to ensure a clean slate (useful for testing and creating isolated states).

func ResetPendingBuiltins

func ResetPendingBuiltins()

ResetPendingBuiltins clears the pending builtins registry (called by ResetModules)

func ResetTypeMetatables

func ResetTypeMetatables()

ResetTypeMetatables clears the type metatable registry (called by ResetModules)

func ResolveRelativeImport

func ResolveRelativeImport(name string, level int, packageName string) (string, error)

ResolveRelativeImport resolves a relative import to an absolute module name. Parameters:

  • name: the module name from the import statement (may be empty for "from . import x")
  • level: number of dots (1 for ".", 2 for "..", etc.)
  • packageName: the current package (__package__ or derived from __name__)

Returns the resolved absolute module name or an error.

func ToGoValue

func ToGoValue(v Value) any

ToGoValue converts a Python value to a Go value

Types

type Block

type Block struct {
	Type          BlockType
	Handler       int // Handler address
	Level         int // Stack level
	ExcStackLevel int // excHandlerStack level at block setup time
}

Block represents a control flow block

type BlockType

type BlockType int

BlockType identifies the type of block

const (
	BlockLoop BlockType = iota
	BlockExcept
	BlockFinally
	BlockWith
	BlockExceptStar
)

type CancelledError

type CancelledError struct{}

CancelledError is returned when script execution is cancelled via context

func (*CancelledError) Error

func (e *CancelledError) Error() string

type CodeFlags

type CodeFlags int

CodeFlags represents flags for code objects

const (
	FlagOptimized         CodeFlags = 1 << iota // Locals are optimized
	FlagNewLocals                               // Use new dict for locals
	FlagVarArgs                                 // *args parameter
	FlagVarKeywords                             // **kwargs parameter
	FlagNested                                  // Nested function
	FlagGenerator                               // Generator function
	FlagNoFree                                  // No free variables
	FlagCoroutine                               // Coroutine function
	FlagIterableCoroutine                       // Iterable coroutine
	FlagAsyncGenerator                          // Async generator
)

type CodeObject

type CodeObject struct {
	Name           string      // Function/class/module name
	Filename       string      // Source filename
	FirstLine      int         // First line number in source
	Code           []byte      // Bytecode instructions
	Constants      []any       // Constant pool
	Names          []string    // Names used in code
	VarNames       []string    // Local variable names
	FreeVars       []string    // Free variables (closures)
	CellVars       []string    // Variables captured in closures
	ArgCount       int         // Number of positional arguments
	KwOnlyArgCount int         // Number of keyword-only arguments
	Flags          CodeFlags   // Code flags
	StackSize      int         // Maximum stack size needed
	LineNoTab      []LineEntry // Line number table
}

CodeObject represents compiled Python code

func (*CodeObject) CellOrFreeName added in v0.3.0

func (co *CodeObject) CellOrFreeName(idx int) string

CellOrFreeName returns the variable name for a cell/free index.

func (*CodeObject) Disassemble

func (co *CodeObject) Disassemble() string

Disassemble returns a human-readable disassembly of the code object

func (*CodeObject) LineForOffset

func (co *CodeObject) LineForOffset(offset int) int

LineForOffset returns the source line for a bytecode offset

type ExceptStarState

type ExceptStarState struct {
	Remaining []*PyException
	Message   string
	IsBase    bool
}

ExceptStarState tracks the remaining unmatched exceptions during except* handling

type Frame

type Frame struct {
	Code              *CodeObject
	IP                int              // Instruction pointer
	Stack             []Value          // Operand stack (pre-allocated)
	SP                int              // Stack pointer (index of next free slot)
	Locals            []Value          // Local variables
	Globals           map[string]Value // Global variables
	EnclosingGlobals  map[string]Value // Enclosing globals (for class bodies)
	Builtins          map[string]Value // Built-in functions
	Cells             []*PyCell        // Closure cells
	BlockStack        []Block          // Block stack for try/except/finally
	OrderedGlobalKeys []string         // Insertion-ordered global names (for class bodies)
}

Frame represents a call frame

type GeneratorState

type GeneratorState int

GeneratorState represents the state of a generator/coroutine

const (
	GenCreated   GeneratorState = iota // Generator created but not started
	GenRunning                         // Generator is currently executing
	GenSuspended                       // Generator is suspended at yield
	GenClosed                          // Generator has finished or was closed
)

type GenericAlias

type GenericAlias struct {
	Origin Value   // The original class/builtin (e.g., list, dict, or a PyClass)
	Args   []Value // The type arguments
}

GenericAlias represents a parameterized type like list[int] or dict[str, int]

func (*GenericAlias) String

func (g *GenericAlias) String() string

func (*GenericAlias) Type

func (g *GenericAlias) Type() string

type GoFunction

type GoFunction func(vm *VM) int

GoFunction is the signature for Go functions callable from Python. Similar to gopher-lua's LGFunction. The function receives the VM and returns the number of values pushed onto the stack.

type Instruction

type Instruction struct {
	Op     Opcode
	Arg    int // Argument value (if HasArg)
	Line   int // Source line number
	Offset int // Byte offset in code
}

Instruction represents a single bytecode instruction with its argument

type LineEntry

type LineEntry struct {
	StartOffset int
	EndOffset   int
	Line        int
}

LineEntry maps bytecode offsets to source lines

type ModuleBuilder

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

ModuleBuilder provides a fluent API for building modules

func NewModuleBuilder

func NewModuleBuilder(name string) *ModuleBuilder

NewModuleBuilder creates a new module builder

func (*ModuleBuilder) Build

func (b *ModuleBuilder) Build() *PyModule

Build returns the constructed module

func (*ModuleBuilder) Const

func (b *ModuleBuilder) Const(name string, value Value) *ModuleBuilder

Const adds a constant value to the module

func (*ModuleBuilder) Doc

func (b *ModuleBuilder) Doc(doc string) *ModuleBuilder

Doc sets the module's docstring

func (*ModuleBuilder) Func

func (b *ModuleBuilder) Func(name string, fn GoFunction) *ModuleBuilder

Func adds a Go function to the module

func (*ModuleBuilder) Method

func (b *ModuleBuilder) Method(name string, fn GoFunction) *ModuleBuilder

Method is an alias for Func

func (*ModuleBuilder) Register

func (b *ModuleBuilder) Register() *PyModule

Register builds and registers the module with the global registry

func (*ModuleBuilder) SubModule

func (b *ModuleBuilder) SubModule(name string, submodule *PyModule) *ModuleBuilder

SubModule adds a submodule to the module

func (*ModuleBuilder) Type

func (b *ModuleBuilder) Type(typeName string, constructor GoFunction, methods map[string]GoFunction) *ModuleBuilder

Type adds a type/class to the module with methods

type ModuleLoader

type ModuleLoader func(vm *VM) *PyModule

ModuleLoader is a function that creates/loads a module

type Opcode

type Opcode byte

Opcode represents a single bytecode instruction

const (
	// Stack manipulation
	OpPop  Opcode = iota // Pop top of stack
	OpDup                // Duplicate top of stack
	OpDup2               // Duplicate top two stack items (for augmented subscript)
	OpRot2               // Swap top two stack items
	OpRot3               // Rotate top three stack items

	// Constants and variables
	OpLoadConst    // Load constant from constants pool (arg: index)
	OpLoadName     // Load variable by name (arg: name index)
	OpStoreName    // Store to variable by name (arg: name index)
	OpDeleteName   // Delete variable by name (arg: name index)
	OpLoadFast     // Load local variable (arg: local index)
	OpStoreFast    // Store to local variable (arg: local index)
	OpDeleteFast   // Delete local variable (arg: local index)
	OpLoadGlobal   // Load global variable (arg: name index)
	OpStoreGlobal  // Store to global variable (arg: name index)
	OpDeleteGlobal // Delete global variable (arg: name index)
	OpLoadAttr     // Load attribute (arg: name index)
	OpStoreAttr    // Store attribute (arg: name index)
	OpDeleteAttr   // Delete attribute (arg: name index)

	// Subscript operations
	OpBinarySubscr // a[b] -> push a[b]
	OpStoreSubscr  // a[b] = c
	OpDeleteSubscr // del a[b]

	// Arithmetic operations
	OpUnaryPositive // +a
	OpUnaryNegative // -a
	OpUnaryNot      // not a
	OpUnaryInvert   // ~a

	OpBinaryAdd      // a + b
	OpBinarySubtract // a - b
	OpBinaryMultiply // a * b
	OpBinaryDivide   // a / b
	OpBinaryFloorDiv // a // b
	OpBinaryModulo   // a % b
	OpBinaryPower    // a ** b
	OpBinaryMatMul   // a @ b
	OpBinaryLShift   // a << b
	OpBinaryRShift   // a >> b
	OpBinaryAnd      // a & b
	OpBinaryOr       // a | b
	OpBinaryXor      // a ^ b

	// In-place operations
	OpInplaceAdd      // a += b
	OpInplaceSubtract // a -= b
	OpInplaceMultiply // a *= b
	OpInplaceDivide   // a /= b
	OpInplaceFloorDiv // a //= b
	OpInplaceModulo   // a %= b
	OpInplacePower    // a **= b
	OpInplaceMatMul   // a @= b
	OpInplaceLShift   // a <<= b
	OpInplaceRShift   // a >>= b
	OpInplaceAnd      // a &= b
	OpInplaceOr       // a |= b
	OpInplaceXor      // a ^= b

	// Comparison operations
	OpCompareEq    // a == b
	OpCompareNe    // a != b
	OpCompareLt    // a < b
	OpCompareLe    // a <= b
	OpCompareGt    // a > b
	OpCompareGe    // a >= b
	OpCompareIs    // a is b
	OpCompareIsNot // a is not b
	OpCompareIn    // a in b
	OpCompareNotIn // a not in b

	// Boolean operations
	OpJumpIfTrueOrPop  // Jump if true, else pop (arg: offset)
	OpJumpIfFalseOrPop // Jump if false, else pop (arg: offset)

	// Control flow
	OpJump           // Unconditional jump (arg: offset)
	OpJumpIfTrue     // Jump if top is true (arg: offset)
	OpJumpIfFalse    // Jump if top is false (arg: offset)
	OpPopJumpIfTrue  // Pop and jump if true (arg: offset)
	OpPopJumpIfFalse // Pop and jump if false (arg: offset)
	OpContinueLoop   // Continue through finally blocks (arg: loop target offset)

	// Iteration
	OpGetIter // Get iterator from iterable
	OpForIter // Get next from iterator or jump (arg: offset)

	// Function operations
	OpMakeFunction // Create function object (arg: flags)
	OpCall         // Call function (arg: arg count)
	OpCallKw       // Call function with keyword args (arg: arg count)
	OpCallEx       // Call function with *args/**kwargs unpacking (arg: flags, 1=has **kwargs)
	OpReturn       // Return from function

	// Class operations
	OpLoadBuildClass // Load __build_class__
	OpLoadMethod     // Load method for call optimization
	OpCallMethod     // Call method (arg: arg count)

	// Collection building
	OpBuildTuple  // Build tuple (arg: count)
	OpBuildList   // Build list (arg: count)
	OpBuildSet    // Build set (arg: count)
	OpBuildMap    // Build dict (arg: count of key-value pairs)
	OpBuildString // Build string from parts (arg: count)

	// Unpacking
	OpUnpackSequence // Unpack sequence (arg: count)
	OpUnpackEx       // Unpack with star (arg: counts before/after)

	// List/set/dict comprehensions
	OpListAppend // Append to list for comprehension
	OpSetAdd     // Add to set for comprehension
	OpMapAdd     // Add to map for comprehension

	// Import operations
	OpImportName // Import module (arg: name index)
	OpImportFrom // Import from module (arg: name index)
	OpImportStar // Import * from module

	// Exception handling
	OpSetupExcept      // Setup exception handler (arg: handler offset)
	OpSetupFinally     // Setup finally handler (arg: handler offset)
	OpPopExcept        // Pop exception handler from block stack
	OpPopBlock         // Pop top block from block stack (for normal finally entry)
	OpEndFinally       // End finally block
	OpRaiseVarargs     // Raise exception (arg: count 0-3)
	OpExceptionMatch   // Check if exception matches type for except clause
	OpClearException   // Clear current exception state (for handler entry)
	OpPopExceptHandler // Pop excHandlerStack entry (end of handler body)

	// Exception groups (except*)
	OpSetupExceptStar   // Setup except* handler (arg: handler offset)
	OpExceptStarMatch   // Match exception group against type: stack [eg, type] → [eg, subgroup_or_None]
	OpExceptStarReraise // Re-raise unmatched exceptions from except* block

	// With statement
	OpSetupWith   // Setup with statement (arg: cleanup offset)
	OpWithCleanup // Cleanup with statement

	// Assertion
	OpAssert // Assert with optional message

	// Closure operations
	OpLoadClosure  // Load closure variable
	OpStoreClosure // Store to closure variable
	OpLoadDeref    // Load from cell
	OpStoreDeref   // Store to cell
	OpDeleteDeref  // Delete cell variable (set to nil)
	OpMakeCell     // Create cell for variable

	// Misc
	OpNop        // No operation
	OpPrintExpr  // Print expression result (REPL)
	OpLoadLocals // Load locals dict

	// Generator operations
	OpYieldValue // Yield value from generator, suspend execution
	OpYieldFrom  // Delegate to sub-iterator (yield from)
	OpGenStart   // Generator frame initialization marker

	// Coroutine operations
	OpGetAwaitable // Get awaitable from object (__await__)
	OpGetAIter     // Get async iterator (__aiter__)
	OpGetANext     // Get next from async iterator (__anext__)

	// Pattern matching operations (match statement)
	OpMatchSequence // Match sequence pattern (arg: expected length, or -1 for variable with star)
	OpMatchMapping  // Match mapping pattern (arg: number of keys)
	OpMatchClass    // Match class pattern (arg: number of positional attrs)
	OpMatchKeys     // Check if mapping has required keys (keys on stack)
	OpCopyDict      // Copy dict for **rest in mapping pattern
	OpGetLen        // Get length of sequence (non-consuming for pattern match)
	OpMatchStar     // Handle starred pattern in sequence (arg: minLength)
	OpExtractStar   // Extract star slice (arg: beforeStar << 8 | afterStar)

	// Specialized LOAD_FAST for common indices (no arg needed)
	OpLoadFast0 // Load local variable 0
	OpLoadFast1 // Load local variable 1
	OpLoadFast2 // Load local variable 2
	OpLoadFast3 // Load local variable 3

	// Specialized STORE_FAST for common indices (no arg needed)
	OpStoreFast0 // Store to local variable 0
	OpStoreFast1 // Store to local variable 1
	OpStoreFast2 // Store to local variable 2
	OpStoreFast3 // Store to local variable 3

	// Specialized constant loading (no arg needed)
	OpLoadNone  // Load None
	OpLoadTrue  // Load True
	OpLoadFalse // Load False
	OpLoadZero  // Load integer 0
	OpLoadOne   // Load integer 1

	// Specialized arithmetic (no arg needed)
	OpIncrementFast  // Increment local by 1 (arg: local index) - has arg!
	OpDecrementFast  // Decrement local by 1 (arg: local index) - has arg!
	OpNegateFast     // Negate local in place (arg: local index) - for sign = -sign
	OpAddConstFast   // Add constant to local (arg: packed local index + const index)
	OpAccumulateFast // Add TOS to local (arg: local index) - for x = x + expr

	// Superinstructions - combined operations
	OpLoadFastLoadFast  // Load two locals (arg: packed indices)
	OpLoadFastLoadConst // Load local then const (arg: packed indices)
	OpStoreFastLoadFast // Store then load (arg: packed indices)
	OpBinaryAddInt      // Add two ints (optimized path)
	OpBinarySubtractInt // Subtract two ints (optimized path)
	OpBinaryMultiplyInt // Multiply two ints (optimized path)
	OpBinaryDivideFloat // True division (always returns float)
	OpBinaryAddFloat    // Float addition
	OpCompareLtInt      // Compare less than for ints
	OpCompareLeInt      // Compare less than or equal for ints
	OpCompareGtInt      // Compare greater than for ints
	OpCompareGeInt      // Compare greater than or equal for ints
	OpCompareEqInt      // Compare equal for ints
	OpCompareNeInt      // Compare not equal for ints

	// Empty collection loading (no arg needed)
	OpLoadEmptyList  // Load empty list []
	OpLoadEmptyTuple // Load empty tuple ()
	OpLoadEmptyDict  // Load empty dict {}

	// Combined compare and jump (superinstructions)
	OpCompareLtJump // Compare < and jump if false (arg: offset)
	OpCompareLeJump // Compare <= and jump if false (arg: offset)
	OpCompareGtJump // Compare > and jump if false (arg: offset)
	OpCompareGeJump // Compare >= and jump if false (arg: offset)
	OpCompareEqJump // Compare == and jump if false (arg: offset)
	OpCompareNeJump // Compare != and jump if false (arg: offset)

	// Compare two locals and jump (ultra-optimized loop conditions)
	// arg format: low 4 bits = local1, next 4 bits = local2, remaining = jump offset >> 4
	OpCompareLtLocalJump // local1 < local2, jump if false

	// Inline builtins (no function call overhead)
	OpLenList    // len(list) - inline
	OpLenString  // len(string) - inline
	OpLenTuple   // len(tuple) - inline
	OpLenDict    // len(dict) - inline
	OpLenGeneric // len() - generic but optimized path

	// More superinstructions
	OpLoadConstLoadFast  // Load const then local (arg: packed indices)
	OpLoadGlobalLoadFast // Load global then local (arg: packed indices)

	// Annotations
	OpSetupAnnotations // Ensure __annotations__ dict exists in current namespace
)

func (Opcode) HasArg

func (op Opcode) HasArg() bool

HasArg returns true if the opcode takes an argument Uses a lookup table for O(1) performance

func (Opcode) String

func (op Opcode) String() string

type PyBool

type PyBool struct {
	Value bool
}

PyBool represents a Python boolean

func NewBool

func NewBool(v bool) *PyBool

NewBool creates a Python bool from a Go bool

func (*PyBool) String

func (b *PyBool) String() string

func (*PyBool) Type

func (b *PyBool) Type() string

type PyBuiltinFunc

type PyBuiltinFunc struct {
	Name  string
	Fn    func(args []Value, kwargs map[string]Value) (Value, error)
	Bound bool // true when self is already captured (bound method wrapper)
}

PyBuiltinFunc represents a built-in function

func (*PyBuiltinFunc) String

func (b *PyBuiltinFunc) String() string

func (*PyBuiltinFunc) Type

func (b *PyBuiltinFunc) Type() string

type PyBytes

type PyBytes struct {
	Value []byte
}

PyBytes represents Python bytes

func NewBytes

func NewBytes(v []byte) *PyBytes

NewBytes creates a Python bytes from a Go byte slice

func (*PyBytes) String

func (b *PyBytes) String() string

func (*PyBytes) Type

func (b *PyBytes) Type() string

type PyCell

type PyCell struct {
	Value Value
}

PyCell represents a cell for closures

type PyClass

type PyClass struct {
	Name                 string
	Bases                []*PyClass
	Dict                 map[string]Value
	Mro                  []*PyClass // Method Resolution Order
	IsABC                bool       // True if class uses ABC abstract method checking
	RegisteredSubclasses []*PyClass // Virtual subclasses registered via ABC.register()
	Metaclass            *PyClass   // Custom metaclass (if any)
	Slots                []string   // nil means no __slots__ (dict allowed); non-nil restricts instance attrs
}

PyClass represents a Python class

func (*PyClass) String

func (c *PyClass) String() string

func (*PyClass) Type

func (c *PyClass) Type() string

type PyClassMethod

type PyClassMethod struct {
	Func Value
}

PyClassMethod wraps a function to bind class as first argument

func (*PyClassMethod) String

func (c *PyClassMethod) String() string

func (*PyClassMethod) Type

func (c *PyClassMethod) Type() string

type PyCode

type PyCode struct {
	Code *CodeObject
}

PyCode wraps a CodeObject for Python access via compile()

func (*PyCode) String

func (c *PyCode) String() string

func (*PyCode) Type

func (c *PyCode) Type() string

type PyComplex

type PyComplex struct {
	Real float64
	Imag float64
}

PyComplex represents a Python complex number

func MakeComplex

func MakeComplex(real, imag float64) *PyComplex

MakeComplex creates a PyComplex value

func NewComplex

func NewComplex(real, imag float64) *PyComplex

NewComplex creates a Python complex from two Go float64s (real, imag)

func (*PyComplex) String

func (c *PyComplex) String() string

func (*PyComplex) Type

func (c *PyComplex) Type() string

type PyCoroutine

type PyCoroutine struct {
	Frame      *Frame         // Suspended frame state
	Code       *CodeObject    // The coroutine's code object
	Name       string         // Coroutine function name
	State      GeneratorState // Current state (reuses generator states)
	YieldValue Value          // Value to send into coroutine on resume
}

PyCoroutine represents a Python coroutine object (async def)

func (*PyCoroutine) String

func (c *PyCoroutine) String() string

func (*PyCoroutine) Type

func (c *PyCoroutine) Type() string

type PyDict

type PyDict struct {
	Items map[Value]Value // Legacy field for compatibility
	// contains filtered or unexported fields
}

PyDict represents a Python dictionary with hash-based lookups

func NewDict

func NewDict() *PyDict

NewDict creates a Python dict

func (*PyDict) DictContains

func (d *PyDict) DictContains(key Value, vm *VM) bool

DictContains checks if a key exists using hash-based lookup

func (*PyDict) DictDelete

func (d *PyDict) DictDelete(key Value, vm *VM) bool

DictDelete removes a key using hash-based lookup

func (*PyDict) DictGet

func (d *PyDict) DictGet(key Value, vm *VM) (Value, bool)

DictGet retrieves a value by key using hash-based lookup

func (*PyDict) DictLen

func (d *PyDict) DictLen() int

DictLen returns the number of items

func (*PyDict) DictSet

func (d *PyDict) DictSet(key, value Value, vm *VM)

DictSet sets a key-value pair using hash-based storage

func (*PyDict) Keys

func (d *PyDict) Keys(vm *VM) []Value

Keys returns keys in insertion order

func (*PyDict) String

func (d *PyDict) String() string

func (*PyDict) Type

func (d *PyDict) Type() string

type PyException

type PyException struct {
	ExcType         *PyClass         // Exception class (e.g., ValueError, TypeError)
	TypeName        string           // Exception type name (used when ExcType is nil)
	Args            *PyTuple         // Exception arguments
	Message         string           // String representation
	Cause           *PyException     // __cause__ for chained exceptions (raise X from Y)
	Context         *PyException     // __context__ for implicit chaining
	SuppressContext bool             // __suppress_context__ - set True when __cause__ is assigned
	Traceback       []TracebackEntry // Traceback frames
	Instance        *PyInstance      // non-nil for ExceptionGroup instances
	Notes           *PyList          // __notes__ list (nil until add_note is called)
}

PyException represents a Python exception

func (*PyException) Error

func (e *PyException) Error() string

func (*PyException) String

func (e *PyException) String() string

func (*PyException) Type

func (e *PyException) Type() string

type PyFloat

type PyFloat struct {
	Value float64
}

PyFloat represents a Python float

func NewFloat

func NewFloat(v float64) *PyFloat

NewFloat creates a Python float from a Go float64

func (*PyFloat) String

func (f *PyFloat) String() string

func (*PyFloat) Type

func (f *PyFloat) Type() string

type PyFrozenSet

type PyFrozenSet struct {
	Items map[Value]struct{} // Legacy field for compatibility
	// contains filtered or unexported fields
}

PyFrozenSet represents an immutable Python frozenset

func (*PyFrozenSet) FrozenSetAdd

func (s *PyFrozenSet) FrozenSetAdd(value Value, vm *VM)

FrozenSetAdd adds a value to the frozenset (used during construction)

func (*PyFrozenSet) FrozenSetContains

func (s *PyFrozenSet) FrozenSetContains(value Value, vm *VM) bool

FrozenSetContains checks if a value exists using hash-based lookup

func (*PyFrozenSet) FrozenSetLen

func (s *PyFrozenSet) FrozenSetLen() int

FrozenSetLen returns the number of items

func (*PyFrozenSet) String

func (s *PyFrozenSet) String() string

func (*PyFrozenSet) Type

func (s *PyFrozenSet) Type() string

type PyFunction

type PyFunction struct {
	Code       *CodeObject
	Globals    map[string]Value
	Defaults   *PyTuple
	KwDefaults map[string]Value // Keyword-only argument defaults
	Closure    []*PyCell
	Name       string
	IsAbstract bool             // Set by @abstractmethod decorator
	Dict       map[string]Value // Custom attributes (e.g. func._name)
}

PyFunction represents a Python function

func (*PyFunction) String

func (f *PyFunction) String() string

func (*PyFunction) Type

func (f *PyFunction) Type() string

type PyGenerator

type PyGenerator struct {
	Frame      *Frame         // Suspended frame state
	Code       *CodeObject    // The generator's code object
	Name       string         // Generator function name
	State      GeneratorState // Current state
	YieldValue Value          // Value to send into generator on resume

	// Saved VM exception state (isolated per-generator)
	SavedCurrentException *PyException
	SavedLastException    *PyException
	SavedExcHandlerStack  []*PyException
	SavedPendingReturn    Value
	SavedHasPendingReturn bool
	SavedPendingJump      int
	SavedHasPendingJump   bool
}

PyGenerator represents a Python generator object

func (*PyGenerator) String

func (g *PyGenerator) String() string

func (*PyGenerator) Type

func (g *PyGenerator) Type() string

type PyGoFunc

type PyGoFunc struct {
	Name string
	Fn   GoFunction
}

PyGoFunc wraps a Go function for use in Python

func NewGoFunction

func NewGoFunction(name string, fn GoFunction) *PyGoFunc

NewGoFunction creates a Python-callable function from a Go function

func (*PyGoFunc) String

func (g *PyGoFunc) String() string

func (*PyGoFunc) Type

func (g *PyGoFunc) Type() string

type PyInstance

type PyInstance struct {
	Class *PyClass
	Dict  map[string]Value // nil when class defines __slots__
	Slots map[string]Value // non-nil when class defines __slots__
}

PyInstance represents an instance of a class

func (*PyInstance) String

func (i *PyInstance) String() string

func (*PyInstance) Type

func (i *PyInstance) Type() string

type PyInt

type PyInt struct {
	Value    int64
	BigValue *big.Int // non-nil for integers that overflow int64
}

PyInt represents a Python integer

func MakeBigInt

func MakeBigInt(v *big.Int) *PyInt

MakeBigInt returns a PyInt from a big.Int value

func MakeInt

func MakeInt(v int64) *PyInt

MakeInt returns a PyInt, using cached values for small integers

func NewInt

func NewInt(v int64) *PyInt

NewInt creates a Python int from a Go int64

func (*PyInt) BigIntValue

func (i *PyInt) BigIntValue() *big.Int

BigIntValue returns the big.Int representation of this integer

func (*PyInt) IsBig

func (i *PyInt) IsBig() bool

IsBig returns true if this integer uses big.Int representation

func (*PyInt) String

func (i *PyInt) String() string

func (*PyInt) Type

func (i *PyInt) Type() string

type PyIterator

type PyIterator struct {
	Items  []Value
	Index  int
	Source *PyList // Optional: if set, Items is dynamically read from Source.Items (for live mutation visibility)
}

PyIterator wraps an iterator

func (*PyIterator) String

func (i *PyIterator) String() string

func (*PyIterator) Type

func (i *PyIterator) Type() string

type PyList

type PyList struct {
	Items []Value
}

PyList represents a Python list

func NewList

func NewList(items []Value) *PyList

NewList creates a Python list from a slice of Values

func (*PyList) String

func (l *PyList) String() string

func (*PyList) Type

func (l *PyList) Type() string

type PyMethod

type PyMethod struct {
	Func     *PyFunction
	Instance Value
}

PyMethod represents a bound method

func (*PyMethod) String

func (m *PyMethod) String() string

func (*PyMethod) Type

func (m *PyMethod) Type() string

type PyModule

type PyModule struct {
	Name    string
	Dict    map[string]Value // Module namespace (__dict__)
	Doc     string           // __doc__
	Package string           // __package__
	Loader  Value            // __loader__
	Spec    Value            // __spec__
}

PyModule represents a Python module

func NewModule

func NewModule(name string) *PyModule

NewModule creates a new module with the given name

func (*PyModule) Get

func (m *PyModule) Get(name string) (Value, bool)

Get retrieves a value from the module by name

func (*PyModule) Set

func (m *PyModule) Set(name string, value Value)

Set sets a value in the module namespace

func (*PyModule) String

func (m *PyModule) String() string

func (*PyModule) Type

func (m *PyModule) Type() string

type PyNone

type PyNone struct{}

PyNone represents Python's None

func (*PyNone) String

func (n *PyNone) String() string

func (*PyNone) Type

func (n *PyNone) Type() string

type PyNotImplementedType

type PyNotImplementedType struct{}

PyNotImplementedType represents Python's NotImplemented singleton

func (*PyNotImplementedType) String

func (n *PyNotImplementedType) String() string

func (*PyNotImplementedType) Type

func (n *PyNotImplementedType) Type() string

type PyObject

type PyObject interface {
	Type() string
	String() string
}

PyObject is the base interface for all Python objects

type PyPanicError

type PyPanicError struct {
	ExcType string // Exception type name (e.g., "TypeError", "ValueError")
	Message string // Error message
}

PyPanicError is used to propagate Python exceptions through Go panics. This type is caught by the VM's recover and converted to a proper PyException.

func (*PyPanicError) Error

func (e *PyPanicError) Error() string

type PyProperty

type PyProperty struct {
	Fget Value
	Fset Value
	Fdel Value
	Doc  string
}

PyProperty represents a Python property descriptor

func (*PyProperty) String

func (p *PyProperty) String() string

func (*PyProperty) Type

func (p *PyProperty) Type() string

type PyRange

type PyRange struct {
	Start, Stop, Step int64
}

PyRange represents a range object

func (*PyRange) Contains

func (r *PyRange) Contains(val int64) bool

Contains returns whether val is in the range

func (*PyRange) Len

func (r *PyRange) Len() int64

Len returns the number of elements in the range

func (*PyRange) String

func (r *PyRange) String() string

func (*PyRange) Type

func (r *PyRange) Type() string

type PySet

type PySet struct {
	Items map[Value]struct{} // Legacy field for compatibility
	// contains filtered or unexported fields
}

PySet represents a Python set with hash-based lookups

func (*PySet) SetAdd

func (s *PySet) SetAdd(value Value, vm *VM)

SetAdd adds a value to the set using hash-based storage

func (*PySet) SetContains

func (s *PySet) SetContains(value Value, vm *VM) bool

SetContains checks if a value exists using hash-based lookup

func (*PySet) SetLen

func (s *PySet) SetLen() int

SetLen returns the number of items

func (*PySet) SetRemove

func (s *PySet) SetRemove(value Value, vm *VM) bool

SetRemove removes a value from the set

func (*PySet) String

func (s *PySet) String() string

func (*PySet) Type

func (s *PySet) Type() string

type PySlice

type PySlice struct {
	Start Value // Can be nil (None) or int
	Stop  Value // Can be nil (None) or int
	Step  Value // Can be nil (None) or int
}

PySlice represents a slice object for slicing sequences

func (*PySlice) String

func (s *PySlice) String() string

func (*PySlice) Type

func (s *PySlice) Type() string

type PyStaticMethod

type PyStaticMethod struct {
	Func Value
}

PyStaticMethod wraps a function to prevent binding

func (*PyStaticMethod) String

func (s *PyStaticMethod) String() string

func (*PyStaticMethod) Type

func (s *PyStaticMethod) Type() string

type PyString

type PyString struct {
	Value string
}

PyString represents a Python string

func InternString

func InternString(s string) *PyString

InternString returns an interned PyString for short strings This allows pointer comparison for equality in many cases

func NewString

func NewString(v string) *PyString

NewString creates a Python str from a Go string, using interning for short strings

func (*PyString) String

func (s *PyString) String() string

func (*PyString) Type

func (s *PyString) Type() string

type PySuper

type PySuper struct {
	ThisClass *PyClass // The class where super() was called (__class__)
	Instance  Value    // The instance (self) or class
	StartIdx  int      // Index in MRO to start searching from (after ThisClass)
}

PySuper represents Python's super() proxy object

func (*PySuper) String

func (s *PySuper) String() string

func (*PySuper) Type

func (s *PySuper) Type() string

type PyTuple

type PyTuple struct {
	Items []Value
}

PyTuple represents a Python tuple

func NewTuple

func NewTuple(items []Value) *PyTuple

NewTuple creates a Python tuple from a slice of Values

func (*PyTuple) String

func (t *PyTuple) String() string

func (*PyTuple) Type

func (t *PyTuple) Type() string

type PyUserData

type PyUserData struct {
	Value     any
	Metatable *PyDict
}

PyUserData wraps arbitrary Go values for use in Python. Similar to gopher-lua's LUserData.

func NewUserData

func NewUserData(v any) *PyUserData

NewUserData creates a new userdata wrapping a Go value

func (*PyUserData) String

func (u *PyUserData) String() string

func (*PyUserData) Type

func (u *PyUserData) Type() string

type TimeoutError

type TimeoutError struct {
	Timeout time.Duration
}

TimeoutError is returned when script execution exceeds the time limit

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

type TracebackEntry

type TracebackEntry struct {
	Filename string
	Line     int
	Function string
}

TracebackEntry represents a single frame in a traceback

type TypeMetatable

type TypeMetatable struct {
	Name       string
	Methods    map[string]GoFunction
	Properties map[string]GoFunction // Getters that are called automatically (like Python @property)
}

TypeMetatable holds methods and properties for a user-defined type

func GetRegisteredTypeMetatable

func GetRegisteredTypeMetatable(typeName string) *TypeMetatable

GetRegisteredTypeMetatable retrieves a type metatable globally (without VM instance)

func (*TypeMetatable) SetMethod

func (mt *TypeMetatable) SetMethod(name string, fn GoFunction)

SetMethod sets a method on a type metatable

func (*TypeMetatable) SetMethods

func (mt *TypeMetatable) SetMethods(methods map[string]GoFunction)

SetMethods sets multiple methods on a type metatable

type VM

type VM struct {
	Globals map[string]Value

	// Filesystem module imports
	SearchPaths  []string                                   // Directories to search for .py modules
	FileImporter func(filename string) (*CodeObject, error) // Callback to compile a .py file (avoids circular dep)
	// contains filtered or unexported fields
}

VM is the Python virtual machine

func NewVM

func NewVM() *VM

NewVM creates a new virtual machine

func (*VM) AllocatedBytes added in v0.3.0

func (vm *VM) AllocatedBytes() int64

AllocatedBytes returns the approximate number of bytes currently tracked.

func (*VM) ApplyPendingBuiltins

func (vm *VM) ApplyPendingBuiltins()

ApplyPendingBuiltins applies any pending builtins to an existing VM. This is useful when enabling modules after VM creation.

func (*VM) ArgError

func (vm *VM) ArgError(n int, msg string)

ArgError raises an argument error

func (*VM) Call

func (vm *VM) Call(callable Value, args []Value, kwargs map[string]Value) (Value, error)

Call calls a Python callable with the given arguments This is the exported version of the internal call method

func (*VM) CallDunder

func (vm *VM) CallDunder(inst *PyInstance, name string, args ...Value) (Value, bool)

CallDunder looks up and calls a dunder method on a PyInstance via MRO. Returns (result, found). If found is false, no method was found. Panics with RaiseError on call errors (matching GoFunction conventions).

func (*VM) CallDunderWithError

func (vm *VM) CallDunderWithError(inst *PyInstance, name string, args ...Value) (Value, bool, error)

CallDunderWithError looks up and calls a dunder method on a PyInstance via MRO. Returns (result, found, error) - for use in PyBuiltinFunc where errors are returned.

func (*VM) CallFunction

func (vm *VM) CallFunction(fn *PyFunction, args []Value, kwargs map[string]Value) (Value, error)

CallFunction calls a PyFunction with the given arguments.

func (*VM) CheckBool

func (vm *VM) CheckBool(n int) bool

CheckBool gets argument n as bool

func (*VM) CheckDict

func (vm *VM) CheckDict(n int) *PyDict

CheckDict gets argument n as a dict

func (*VM) CheckFloat

func (vm *VM) CheckFloat(n int) float64

CheckFloat gets argument n as float64, raises error if not convertible

func (*VM) CheckInt

func (vm *VM) CheckInt(n int) int64

CheckInt gets argument n as int64, raises error if not convertible

func (*VM) CheckList

func (vm *VM) CheckList(n int) *PyList

CheckList gets argument n as a list

func (*VM) CheckString

func (vm *VM) CheckString(n int) string

CheckString gets argument n as string, raises error if not a string

func (*VM) CheckUserData

func (vm *VM) CheckUserData(n int, typeName string) *PyUserData

CheckUserData gets argument n as userdata, checking the metatable name

func (*VM) CompareOp

func (vm *VM) CompareOp(op Opcode, a, b Value) Value

CompareOp performs a comparison operation (exported wrapper)

func (*VM) ComputeC3MRO

func (vm *VM) ComputeC3MRO(class *PyClass, bases []*PyClass) ([]*PyClass, error)

ComputeC3MRO computes the Method Resolution Order using C3 linearization algorithm. This properly handles multiple inheritance and detects inconsistent hierarchies.

func (*VM) CoroutineSend

func (vm *VM) CoroutineSend(coro *PyCoroutine, value Value) (Value, bool, error)

CoroutineSend resumes a coroutine with a value (same as generator but for coroutines)

func (*VM) CoroutineThrow

func (vm *VM) CoroutineThrow(coro *PyCoroutine, excType, excValue Value) (Value, bool, error)

CoroutineThrow throws an exception into a coroutine

func (*VM) DefaultClassCall added in v0.3.0

func (vm *VM) DefaultClassCall(cls *PyClass, args []Value, kwargs map[string]Value) (Value, error)

DefaultClassCall calls the default class instantiation logic (abstract check → __new__ → __init__).

func (*VM) Equal

func (vm *VM) Equal(a, b Value) bool

Equal tests equality of two Python values (exported wrapper)

func (*VM) EvalInNamespace

func (vm *VM) EvalInNamespace(code *CodeObject, globals, locals map[string]Value) (Value, error)

EvalInNamespace evaluates code and returns the result

func (*VM) Execute

func (vm *VM) Execute(code *CodeObject) (Value, error)

Execute runs bytecode and returns the result

func (*VM) ExecuteInModule

func (vm *VM) ExecuteInModule(code *CodeObject, mod *PyModule) error

ExecuteInModule runs bytecode with a module's dict as the global namespace. This is used to populate a module's namespace when registering Python modules.

func (*VM) ExecuteInNamespace

func (vm *VM) ExecuteInNamespace(code *CodeObject, globals, locals map[string]Value) error

ExecuteInNamespace executes code with custom globals/locals

func (*VM) ExecuteWithContext

func (vm *VM) ExecuteWithContext(ctx context.Context, code *CodeObject) (Value, error)

ExecuteWithContext runs bytecode with a context for cancellation/timeout support. The context is checked periodically during execution (see SetCheckInterval). Returns CancelledError if the context is cancelled, or TimeoutError if it times out.

func (*VM) ExecuteWithTimeout

func (vm *VM) ExecuteWithTimeout(timeout time.Duration, code *CodeObject) (Value, error)

ExecuteWithTimeout runs bytecode with a time limit. Returns TimeoutError if the script exceeds the specified duration.

func (*VM) GeneratorClose

func (vm *VM) GeneratorClose(gen *PyGenerator) error

GeneratorClose closes a generator

func (*VM) GeneratorSend

func (vm *VM) GeneratorSend(gen *PyGenerator, value Value) (Value, bool, error)

GeneratorSend resumes a generator with a value and returns the next yielded value Returns (value, done, error) where done is true if the generator finished

func (*VM) GeneratorThrow

func (vm *VM) GeneratorThrow(gen *PyGenerator, excType, excValue Value) (Value, bool, error)

GeneratorThrow throws an exception into a generator

func (*VM) Get

func (vm *VM) Get(idx int) Value

Get returns the value at the given stack index (1-based, like Lua) Negative indices count from top

func (*VM) GetBuiltin

func (vm *VM) GetBuiltin(name string) Value

GetBuiltin gets a builtin

func (*VM) GetGlobal

func (vm *VM) GetGlobal(name string) Value

GetGlobal gets a global variable

func (*VM) GetIntIndex

func (vm *VM) GetIntIndex(v Value) (int64, error)

GetIntIndex exports getIntIndex for use by stdlib packages.

func (*VM) GetModule

func (vm *VM) GetModule(name string) (*PyModule, bool)

GetModule retrieves a loaded module by name

func (*VM) GetTop

func (vm *VM) GetTop() int

GetTop returns the index of the top element (number of elements on stack)

func (*VM) GetTypeMetatable

func (vm *VM) GetTypeMetatable(typeName string) *TypeMetatable

GetTypeMetatable retrieves a registered type metatable

func (*VM) HashValue

func (vm *VM) HashValue(v Value) uint64

HashValue returns the hash of a Python value (exported wrapper)

func (*VM) ImportModule

func (vm *VM) ImportModule(name string) (*PyModule, error)

ImportModule imports a module by name

func (*VM) IsInstanceOf

func (vm *VM) IsInstanceOf(inst *PyInstance, cls *PyClass) bool

IsInstanceOf checks if an instance is an instance of a class (including subclasses via MRO).

func (*VM) MaxCollectionSize added in v0.3.0

func (vm *VM) MaxCollectionSize() int64

MaxCollectionSize returns the current collection size limit. 0 means unlimited.

func (*VM) MaxMemoryBytes added in v0.3.0

func (vm *VM) MaxMemoryBytes() int64

MaxMemoryBytes returns the current memory limit. 0 means unlimited.

func (*VM) MaxRecursionDepth added in v0.3.0

func (vm *VM) MaxRecursionDepth() int64

MaxRecursionDepth returns the current maximum recursion depth. 0 means unlimited.

func (*VM) NewTypeMetatable

func (vm *VM) NewTypeMetatable(typeName string) *TypeMetatable

NewTypeMetatable creates a new type metatable

func (*VM) NewUserDataWithMeta

func (vm *VM) NewUserDataWithMeta(v any, typeName string) *PyUserData

NewUserDataWithMeta creates userdata with a metatable attached

func (*VM) OptionalBool

func (vm *VM) OptionalBool(pos int, def bool) bool

OptionalBool returns the bool at stack position pos if present and not None, otherwise returns def.

func (*VM) OptionalFloat

func (vm *VM) OptionalFloat(pos int, def float64) float64

OptionalFloat returns the float at stack position pos if present and not None, otherwise returns def.

func (*VM) OptionalInt

func (vm *VM) OptionalInt(pos int, def int64) int64

OptionalInt returns the int at stack position pos if present and not None, otherwise returns def.

func (*VM) OptionalString

func (vm *VM) OptionalString(pos int, def string) string

OptionalString returns the string at stack position pos if present and not None, otherwise returns def.

func (*VM) Pop

func (vm *VM) Pop() Value

Pop pops and returns a value from the stack

func (*VM) Push

func (vm *VM) Push(v Value)

Push pushes a value onto the stack

func (*VM) RaiseError

func (vm *VM) RaiseError(format string, args ...any)

RaiseError raises a Python-style error. The format string can optionally start with an exception type prefix like "ValueError: ".

func (*VM) Register

func (vm *VM) Register(name string, fn GoFunction)

Register registers a Go function as a global

func (*VM) RegisterBuiltin

func (vm *VM) RegisterBuiltin(name string, fn GoFunction)

RegisterBuiltin registers a Go function as a builtin

func (*VM) RegisterFuncs

func (vm *VM) RegisterFuncs(funcs map[string]GoFunction)

RegisterFuncs registers multiple functions at once

func (*VM) RegisterModule

func (vm *VM) RegisterModule(name string, loader ModuleLoader)

RegisterModule registers a module loader on the VM

func (*VM) RegisterModuleInstance

func (vm *VM) RegisterModuleInstance(name string, module *PyModule)

RegisterModuleInstance directly registers a pre-built module

func (*VM) RegisterType

func (vm *VM) RegisterType(typeName string, constructor GoFunction, methods map[string]GoFunction)

RegisterType is a convenience function to register a Go type with methods Usage:

vm.RegisterType("person", map[string]GoFunction{
    "new": newPerson,
    "name": personGetName,
    "set_name": personSetName,
})

func (*VM) Repr

func (vm *VM) Repr(v Value) string

Repr returns the repr() string for a value

func (*VM) RequireArgs

func (vm *VM) RequireArgs(name string, min int) bool

RequireArgs checks that at least min arguments were passed. If not, it raises a TypeError with the function name and returns false. Usage:

if !vm.RequireArgs("loads", 1) { return 0 }

func (*VM) Run

func (vm *VM) Run(code *CodeObject) (Value, error)

Run executes Python source code

func (*VM) SetBuiltin

func (vm *VM) SetBuiltin(name string, v Value)

SetBuiltin registers a builtin function

func (*VM) SetCheckInterval

func (vm *VM) SetCheckInterval(n int64)

SetCheckInterval sets how often the VM checks for timeout/cancellation. Lower values are more responsive but have more overhead. Default is 1000 instructions.

func (*VM) SetGlobal

func (vm *VM) SetGlobal(name string, v Value)

SetGlobal sets a global variable

func (*VM) SetMaxCollectionSize added in v0.3.0

func (vm *VM) SetMaxCollectionSize(n int64)

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

func (*VM) SetMaxMemoryBytes added in v0.3.0

func (vm *VM) SetMaxMemoryBytes(n int64)

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

func (*VM) SetMaxRecursionDepth added in v0.3.0

func (vm *VM) SetMaxRecursionDepth(n int64)

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

func (*VM) SetTop

func (vm *VM) SetTop(n int)

SetTop sets the stack top to a specific index

func (*VM) ToBool

func (vm *VM) ToBool(n int) bool

ToBool converts argument n to bool

func (*VM) ToFloat

func (vm *VM) ToFloat(n int) float64

ToFloat converts argument n to float64

func (*VM) ToInt

func (vm *VM) ToInt(n int) int64

ToInt converts argument n to int64, returns 0 if not convertible

func (*VM) ToList

func (vm *VM) ToList(v Value) ([]Value, error)

ToList converts a Python iterable to a Go slice of Values (exported wrapper). Handles lists, tuples, strings, ranges, sets, dicts, iterators, generators, etc.

func (*VM) ToString

func (vm *VM) ToString(n int) string

ToString converts argument n to string

func (*VM) ToUserData

func (vm *VM) ToUserData(n int) *PyUserData

ToUserData gets argument n as userdata

func (*VM) TrackAlloc added in v0.3.0

func (vm *VM) TrackAlloc(n int64) error

TrackAlloc is the exported wrapper of trackAlloc for stdlib use.

func (*VM) Truthy

func (vm *VM) Truthy(v Value) bool

Truthy returns whether a Python value is truthy (exported wrapper)

func (*VM) TypeError

func (vm *VM) TypeError(expected string, got Value)

TypeError raises a type error

func (*VM) TypeNameOf

func (vm *VM) TypeNameOf(v Value) string

TypeNameOf returns the Python type name for a value.

type Value

type Value any

Value represents a Python value

func FromGoValue

func FromGoValue(v any) Value

FromGoValue converts a Go value to a Python value

Jump to

Keyboard shortcuts

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