Skip to main content

MontyObject

Enum MontyObject 

Source
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

§type_name: String

Type name for repr (e.g., “os.stat_result”).

§field_names: Vec<String>

Field names in order.

§values: Vec<Self>

Values in order (same length as field_names).

§

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

§exc_type: ExcType

The exception type (e.g., ValueError, TypeError).

§arg: Option<String>

Optional string argument passed to the exception constructor.

§

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

§name: String

The class name (e.g., “Point”, “User”).

§type_id: u64

Identifier of the type, from id(type(dc)) in python.

§field_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.

§

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

§name: String

The function name (used for repr, error messages, and function call identification).

§docstring: Option<String>

Optional docstring for the function.

§

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

Source

pub fn dict(dict: impl Into<DictPairs>) -> Self

Creates a new MontyObject from something that can be converted into a DictPairs.

Source

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.

Source

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.

Source

pub fn py_repr(&self) -> String

Returns the Python repr() string for this value.

§Panics

Could panic if out of memory.

Source

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:

  • None and Ellipsis
  • False
  • Zero numeric values (0, 0.0)
  • Empty sequences and collections ("", b"", [], (), {})

All other values are truthy, including Exception and Repr variants.

Source

pub fn type_name(&self) -> &'static str

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__.

Trait Implementations§

Source§

impl AsRef<MontyObject> for MontyObject

Source§

fn as_ref(&self) -> &Self

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Clone for MontyObject

Source§

fn clone(&self) -> MontyObject

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for MontyObject

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for MontyObject

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for MontyObject

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for MontyObject

Source§

impl From<MontyObject> for NameLookupResult

Source§

fn from(value: MontyObject) -> Self

Converts to this type from the input type.
Source§

impl From<MontyObject> for ExtFunctionResult

Source§

fn from(value: MontyObject) -> Self

Converts to this type from the input type.
Source§

impl Hash for MontyObject

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for MontyObject

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Serialize for MontyObject

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl ToMontyObject for 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.

Source§

type Error = ConversionError

The type returned in the event of a conversion error.
Source§

fn try_from(value: &MontyObject) -> Result<Self, Self::Error>

Performs the conversion.
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.

Source§

type Error = ConversionError

The type returned in the event of a conversion error.
Source§

fn try_from(value: &MontyObject) -> Result<Self, Self::Error>

Performs the conversion.
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.

Source§

type Error = ConversionError

The type returned in the event of a conversion error.
Source§

fn try_from(value: &MontyObject) -> Result<Self, Self::Error>

Performs the conversion.
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).

Source§

type Error = ConversionError

The type returned in the event of a conversion error.
Source§

fn try_from(value: &MontyObject) -> Result<Self, Self::Error>

Performs the conversion.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.