pub enum MontyObject {
Show 28 variants
Ellipsis,
NotImplemented,
None,
Bool(bool),
Int(i64),
BigInt(BigInt),
Float(f64),
String(String),
Bytes(Vec<u8>),
List(Vec<Self>),
Tuple(Vec<Self>),
NamedTuple {
type_name: String,
field_names: Vec<String>,
values: Vec<Self>,
},
Dict(DictPairs),
Set(Vec<Self>),
FrozenSet(Vec<Self>),
Date(MontyDate),
DateTime(MontyDateTime),
TimeDelta(MontyTimeDelta),
TimeZone(MontyTimeZone),
Exception {
exc_type: ExcType,
arg: Option<String>,
},
Type(MontyType),
BuiltinFunction(BuiltinsFunctions),
Path(String),
FileHandle(MontyFileHandle),
Dataclass {
name: String,
type_id: u64,
field_names: Vec<String>,
attrs: DictPairs,
frozen: bool,
},
Function {
name: String,
docstring: Option<String>,
},
Repr(String),
Cycle(usize, String),
}Expand description
An owned Python value exchanged between Monty and its host.
Construct MontyObject values to provide globals, external-function
results, and other inputs to sandboxed code. Execution results and values
passed to host callbacks use the same representation.
Most common Python values have a direct variant, including nested
collections and datetime values. Repr and
Cycle can only appear in output because they cannot be
reconstructed as executable Python values. Exception
can be used both to raise an exception and to represent one returned by
execution.
Collections are owned snapshots: modifying a returned MontyObject does
not modify the corresponding value in a running session.
§Hashability
Only immutable variants implement Hash, including the datetime family
(Date, DateTime, TimeDelta, TimeZone). Attempting to hash mutable
variants (List, Dict) will panic.
§Serialization
The derived Serialize / Deserialize impls use an externally tagged
format ({"Int": 42}, {"String": "hi"}, …). This is what postcard
and serde_json::to_string(&obj) produce. It is lossless and designed
for snapshots and binary transport, not for human-facing JSON.
Variants§
Ellipsis
Python’s Ellipsis singleton (...).
NotImplemented
Python’s NotImplemented singleton.
None
Python’s None singleton.
Bool(bool)
Python boolean (True or False).
Int(i64)
Python integer (64-bit signed).
BigInt(BigInt)
Python arbitrary-precision integer (larger than i64).
Float(f64)
Python float (64-bit IEEE 754).
String(String)
Python string (UTF-8).
Bytes(Vec<u8>)
Python bytes object.
List(Vec<Self>)
Python list (mutable sequence).
Tuple(Vec<Self>)
Python tuple (immutable sequence).
NamedTuple
Python named tuple (immutable sequence with named fields).
Named tuples behave like tuples but also support attribute access by field name. The type_name is used in repr (e.g., “os.stat_result”), and field_names provides the attribute names for each position.
Fields
Dict(DictPairs)
Python dictionary (insertion-ordered mapping).
Set(Vec<Self>)
Python set (mutable, unordered collection of unique elements).
FrozenSet(Vec<Self>)
Python frozenset (immutable, unordered collection of unique elements).
Date(MontyDate)
Python datetime.date.
DateTime(MontyDateTime)
Python datetime.datetime.
TimeDelta(MontyTimeDelta)
Python datetime.timedelta.
TimeZone(MontyTimeZone)
Python datetime.timezone fixed-offset timezone.
Exception
Python exception with type and optional message argument.
Fields
Type(MontyType)
A Python type object (e.g., int, str, list).
Returned by the type() builtin and can be compared with other types.
BuiltinFunction(BuiltinsFunctions)
Path(String)
Python pathlib.Path object (or technically a PurePosixPath).
Represents a filesystem path. Can be used both as input (from host) and output.
FileHandle(MontyFileHandle)
An open file object (the result of open()).
Dataclass
A dataclass instance with class name, field names, attributes, and mutability.
Method calls are detected lazily at runtime: when call_attr is invoked
on a dataclass and the attribute name is not found in attrs, it is
dispatched as a MethodCall to the host (provided the name is public).
Fields
Function
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. When called, the VM yields FunctionCall to the host.
Fields
Repr(String)
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 to the interpreter.
Cycle(usize, String)
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 an opaque identity token
(the raw heap index of the object the cycle points back to — meaningful only
for equality, and only within the result that produced it) and the
type-specific placeholder string (e.g., "[...]" for lists, "{...}" for
dicts). Two Cycle values compare equal if they refer to the same object.
This is output-only and cannot be used as an input to the interpreter.
Implementations§
Source§impl MontyObject
impl MontyObject
Sourcepub fn dict(dict: impl Into<DictPairs>) -> Self
pub fn dict(dict: impl Into<DictPairs>) -> Self
Creates a new MontyObject from something that can be converted into a DictPairs.
Sourcepub fn builtin_function_from_name(name: &str) -> Option<Self>
pub fn builtin_function_from_name(name: &str) -> Option<Self>
Resolves a builtin function by its Python name (e.g. "len").
The BuiltinsFunctions enum inside MontyObject::BuiltinFunction is
crate-private, so boundaries that serialize a builtin function by name
(e.g. the subprocess wire protocol) use this to reconstruct the variant.
The name matches the variant’s Display output.
Sourcepub fn host_size(&self) -> usize
pub fn host_size(&self) -> usize
Shallow host footprint of a freshly decoded obj: the fixed MontyObject
size plus any leaf payload it owns directly (string/bytes/bigint bytes, and
the Vec<String> field names of structured values, which aren’t themselves
MontyObjects and would otherwise be uncharged). Container elements are
excluded — each charges its own size via monty-proto’s decode_field, so a list charges
88 bytes here.
Sourcepub fn is_truthy(&self) -> bool
pub fn is_truthy(&self) -> bool
Returns true 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"",[],(),{})
All other values are truthy, including Exception and Repr variants.
Trait Implementations§
Source§impl AsRef<MontyObject> for MontyObject
impl AsRef<MontyObject> for MontyObject
Source§impl Clone for MontyObject
impl Clone for MontyObject
Source§fn clone(&self) -> MontyObject
fn clone(&self) -> MontyObject
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl Debug for MontyObject
impl Debug for MontyObject
Source§impl<'de> Deserialize<'de> for MontyObject
impl<'de> Deserialize<'de> for MontyObject
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Source§impl Display for MontyObject
impl Display for MontyObject
impl Eq for MontyObject
Source§impl From<MontyObject> for NameLookupResult
impl From<MontyObject> for NameLookupResult
Source§fn from(value: MontyObject) -> Self
fn from(value: MontyObject) -> Self
Source§impl From<MontyObject> for ExtFunctionResult
impl From<MontyObject> for ExtFunctionResult
Source§fn from(value: MontyObject) -> Self
fn from(value: MontyObject) -> Self
Source§impl Hash for MontyObject
impl Hash for MontyObject
Source§impl PartialEq for MontyObject
impl PartialEq for MontyObject
Source§impl Serialize for MontyObject
impl Serialize for MontyObject
Source§impl ToMontyObject for MontyObject
impl ToMontyObject for MontyObject
fn into_monty_object(self) -> MontyObject
Source§impl TryFrom<&MontyObject> for i64
Attempts to convert a MontyObject to an i64 integer.
Returns an error if the object is not an Int variant.
impl TryFrom<&MontyObject> for i64
Attempts to convert a MontyObject to an i64 integer. Returns an error if the object is not an Int variant.
Source§type Error = ConversionError
type Error = ConversionError
Source§impl TryFrom<&MontyObject> for f64
Attempts to convert a MontyObject to an f64 float.
Returns an error if the object is not a Float or Int variant.
Int values are automatically converted to f64 to match python’s behavior.
impl TryFrom<&MontyObject> for f64
Attempts to convert a MontyObject to an f64 float. Returns an error if the object is not a Float or Int variant. Int values are automatically converted to f64 to match python’s behavior.
Source§type Error = ConversionError
type Error = ConversionError
Source§impl TryFrom<&MontyObject> for String
Attempts to convert a MontyObject to a String.
Returns an error if the object is not a heap-allocated Str variant.
impl TryFrom<&MontyObject> for String
Attempts to convert a MontyObject to a String. Returns an error if the object is not a heap-allocated Str variant.
Source§type Error = ConversionError
type Error = ConversionError
Source§impl TryFrom<&MontyObject> for bool
Attempts to convert a MontyObject to a bool.
Returns an error if the object is not a True or False variant.
Note: This does NOT use Python’s truthiness rules (use MontyObject::bool for that).
impl TryFrom<&MontyObject> for bool
Attempts to convert a MontyObject to a bool.
Returns an error if the object is not a True or False variant.
Note: This does NOT use Python’s truthiness rules (use MontyObject::bool for that).