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
Value
Internal undefined value marker
Value
Python’s
Ellipsis singleton (...)Value
Python’s
None singletonValue
Python boolean (
True or False)Value
Python integer (64-bit signed)
Value
Python float (64-bit IEEE 754)
Value
An interned string literal. The
StringId references the string in the Interns table. To get the actual string content, use interns.get(string_id).Value
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).Value
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.Value
A builtin function or exception type
Value
A function from a module (not a global builtin). Module functions require importing a module to access (e.g.,
asyncio.gather).Value
A function defined in the module (not a closure, doesn’t capture any variables)
Value
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.Value
A marker value representing special objects like sys.stdout/stderr. These exist but have minimal functionality in the sandboxed environment.
Value
A property descriptor that computes its value when accessed. When retrieved via
py_getattr, the property’s getter is invoked.Value
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.Value
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
MontyObject
Python’s
Ellipsis singleton (...)MontyObject
Python’s
None singletonMontyObject
Python boolean (
True or False)MontyObject
Python integer (64-bit signed)
MontyObject
Python arbitrary-precision integer (larger than i64)
MontyObject
Python float (64-bit IEEE 754)
MontyObject
Python string (UTF-8)
MontyObject
Python bytes object
MontyObject
Python list (mutable sequence)
MontyObject
Python tuple (immutable sequence)
MontyObject
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)
MontyObject
Python dictionary (insertion-ordered mapping)
MontyObject
Python set (mutable, unordered collection of unique elements)
MontyObject
Python frozenset (immutable, unordered collection of unique elements)
MontyObject
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
MontyObject
A Python type object (e.g.,
int, str, list). Returned by the type() builtin and can be compared with other types.MontyObject
A builtin function reference
MontyObject
Python
pathlib.Path object (or technically a PurePosixPath). Represents a filesystem path. Can be used both as input (from host) and output.MontyObject
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
MontyObject
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
MontyObject
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.MontyObject
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.
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.
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__.
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": "..."}
