Value & MontyObject
Value
Primary value type representing Python objects at runtime. This enum uses a hybrid design: small immediate values (Int, Bool, None) are stored inline, while heap-allocated values (List, Str, Dict, etc.) are stored in the arena and referenced via Ref(HeapId).
Clone is intentionally NOT derived. Use clone_with_heap() for heap values or clone_immediate() for immediate values only. Direct cloning via .clone() would bypass reference counting and cause memory leaks.Variants
Internal undefined value marker
Python’s
Ellipsis singleton (...)Python’s
None singletonPython boolean (
True or False)Python integer (64-bit signed)
Python float (64-bit IEEE 754)
An interned string literal. The
StringId references the string in the Interns table. To get the actual string content, use interns.get(string_id).An interned bytes literal. The
BytesId references the bytes in the Interns table. To get the actual bytes content, use interns.get_bytes(bytes_id).An interned long integer literal. The
LongIntId references the BigInt in the Interns table. Used for integer literals exceeding i64 range. Converted to heap-allocated LongInt on load.A builtin function or exception type
A function from a module (not a global builtin). Module functions require importing a module to access (e.g.,
asyncio.gather).A function defined in the module (not a closure, doesn’t capture any variables)
Reference to an external function defined on the host. The
StringId stores the interned function name. When called, the VM yields a FrameExit::ExternalCall with this StringId so the host can look up and execute the function by name.A marker value representing special objects like sys.stdout/stderr. These exist but have minimal functionality in the sandboxed environment.
A property descriptor that computes its value when accessed. When retrieved via
py_getattr, the property’s getter is invoked.A pending external function call result. Created when the host calls
run_pending() instead of run(result) for an external function call. The CallId correlates with the call that created it. When awaited, blocks the task until the host provides a result via resume(). ExternalFutures follow single-shot semantics like coroutines - awaiting an already-awaited ExternalFuture raises RuntimeError.Heap-allocated values (stored in arena)
MontyObject
A Python value that can be passed to or returned from the interpreter. This is the public-facing type for Python values. It owns all its data and can be freely cloned, serialized, or stored. Unlike the internalValue type, MontyObject does not require a heap for operations.
Input vs Output Variants
Most variants can be used both as inputs (passed torun()) and outputs (returned from execution). However:
Repris output-only: represents values that have no directMontyObjectmappingExceptioncan be used as input (to raise) or output (when code raises)
Variants
Python’s
Ellipsis singleton (...)Python’s
None singletonPython boolean (
True or False)Python integer (64-bit signed)
Python arbitrary-precision integer (larger than i64)
Python float (64-bit IEEE 754)
Python string (UTF-8)
Python bytes object
Python list (mutable sequence)
Python tuple (immutable sequence)
Python named tuple (immutable sequence with named fields). Named tuples behave like tuples but also support attribute access by field name.Fields:
type_name: String- Type name for repr (e.g., “os.stat_result”)field_names: Vec<String>- Field names in ordervalues: Vec<MontyObject>- Values in order (same length as field_names)
Python dictionary (insertion-ordered mapping)
Python set (mutable, unordered collection of unique elements)
Python frozenset (immutable, unordered collection of unique elements)
Python exception with type and optional message argumentFields:
exc_type: ExcType- The exception type (e.g.,ValueError,TypeError)arg: Option<String>- Optional string argument passed to the exception constructor
A Python type object (e.g.,
int, str, list). Returned by the type() builtin and can be compared with other types.A builtin function reference
Python
pathlib.Path object (or technically a PurePosixPath). Represents a filesystem path. Can be used both as input (from host) and output.A dataclass instance with class name, field names, attributes, and mutabilityFields:
name: String- The class name (e.g., “Point”, “User”)type_id: u64- Identifier of the type, fromid(type(dc))in pythonfield_names: Vec<String>- Declared field names in definition order (for repr)attrs: DictPairs- All attribute name → value mapping (includes fields and extra attrs)frozen: bool- Whether this dataclass instance is immutable
An external function provided by the host. Returned by the host in response to a
NameLookup to provide a callable that the VM can invoke.Fields:name: String- The function name (used for repr, error messages, and function call identification)docstring: Option<String>- Optional docstring for the function
Fallback for values that cannot be represented as other variants. Contains the
repr() string of the original value. This is output-only and cannot be used as an input.Represents a cycle detected during Value-to-MontyObject conversion. When converting cyclic structures (e.g.,
a = []; a.append(a)), this variant is used to break the infinite recursion. Contains the heap ID and the type-specific placeholder string (e.g., "[...]" for lists, "{...}" for dicts). This is output-only.Methods
py_repr()
Returns the Pythonrepr() string for this value.
String
The repr string representation
is_truthy()
Returnstrue if this value is “truthy” according to Python’s truth testing rules.
In Python, the following values are considered falsy:
NoneandEllipsisFalse- Zero numeric values (
0,0.0) - Empty sequences and collections (
"",b"",[],(),{})
Exception and Repr variants.
bool
True if the value is truthy
type_name()
Returns the Python type name for this value (e.g.,"int", "str", "list").
These are the same names returned by Python’s type(x).__name__.
&'static str
The type name
Hashability
Only immutable variants (None, Ellipsis, Bool, Int, Float, String, Bytes) implement Hash. Attempting to hash mutable variants (List, Dict) will panic.
JSON Serialization
MontyObject supports JSON serialization with natural mappings:
Bidirectional (can serialize and deserialize):
None↔ JSONnullBool↔ JSONtrue/falseInt↔ JSON integerFloat↔ JSON floatString↔ JSON stringList↔ JSON arrayDict↔ JSON object (keys must be strings)
Ellipsis→{"$ellipsis": true}Tuple→{"$tuple": [...]}Bytes→{"$bytes": [...]}Exception→{"$exception": {"type": "...", "arg": "..."}}Repr→{"$repr": "..."}
