Expand description
§monty-types
Shared boundary types for Monty, the sandboxed Python interpreter — the owned, heap-free data types that cross between the interpreter and the hosts that embed it, with no interpreter implementation.
§What’s here
MontyObject/MontyType— Python values and their types at the host boundary, including thedatetimefamily (MontyDate,MontyDateTime,MontyTimeDelta,MontyTimeZone),DictPairsandMontyFileHandle.MontyException/ExcType— exceptions with tracebacks (StackFrame,CodeLoc) and structured payloads (ExcData).OsFunctionCall— the typed OS-call payloads sandboxed code suspends with (file reads/writes,open(),os.getenv, …), plus thestat_resultbuilders hosts use to answer them.ResourceTracker/ResourceLimits— the resource tracker the interpreter uses to enforce time/memory/recursion limits.PrintStream/PrintWriter—print()output capture.CompileOptions,ExtFunctionResult,NameLookupResult,FileMode, and the CPython-compatible formatting helpers behind theirrepr()s.
§Who should depend on it
Host-side crates that need these types without linking the interpreter —
monty-fs (which services OsFunctionCalls locally via
MountTable::handle_os_call), monty-pool (which talks to Monty workers
over the wire), the pydantic-monty-client Python bindings and the
@pydantic/monty JS bindings — depend on this crate instead of monty,
so their binaries never link the interpreter itself. Only worker-side crates
(monty-runtime, monty-wasm-runtime, and monty-proto with its worker
feature) link monty.
use monty_types::MontyObject;
let value = MontyObject::List(vec![MontyObject::Int(1), MontyObject::String("x".to_owned())]);
assert_eq!(value.py_repr(), "[1, 'x']");§Monty crates
monty— the core interpreter: Python parser, bytecode VM, and sandbox.monty-types— the shared boundary data types (values, exceptions, OS calls, resource limits) hosts use without linking the interpreter. this cratemonty-fs— host-side filesystem mounts: maps virtual sandbox paths to real host directories.monty-runtime— themontybinary: REPL, file runner, and subprocess worker mode.monty-pool— an elastic pool of crash-isolatedmontyworker subprocesses.monty-proto— the protobuf wire protocol spoken between pool parents and workers.monty-type-checking— type checking of sandboxed code, powered by ty.monty-typeshed— the trimmed typeshed stubs describing the stdlib subset Monty implements.monty-macros— the proc macros behindmonty’s argument parsing.
§License
MIT
Re-exports§
pub use crate::format::FormatFloat;pub use crate::format::StringRepr;pub use crate::format::bytes_repr;pub use crate::format::bytes_repr_fmt;pub use crate::format::string_repr_fmt;pub use crate::format::utf8_error_reason;
Modules§
- args
ToArgs/ToMontyObject— projection of typed args structs into the(positional, keyword)MontyObjectpairs host callbacks consume. The#[derive(ToArgs)]macro inmonty-macrosemits impls of these traits viacrate::args::…paths, which resolve in this crate.- format
- Pure CPython-compatible formatting helpers shared by the boundary types:
string/bytes
repr()escaping, shortest-round-trip float rendering, and timezone-offsettimedeltareprs.
Structs§
- CodeLoc
- A line and column position in source code.
- Compile
Options - Options controlling how Monty behavior diverges from plain CPython.
- Conversion
Error - Error returned when a
MontyObjectcannot be converted to the requested Rust type. - Dict
Pairs - A collection of key-value pairs representing Python dictionary contents.
- Getenv
Args os.getenv(key, default=None)shape. The host decides whether to substitutedefaultwhen the variable is unset.- Json
Error Data - Structured fields of a
json.JSONDecodeError, mirroring CPython’smsg/doc/pos/lineno/colnoexception attributes. - Mkdir
Call Args mkdir(path, parents=False, exist_ok=False)shape.parents/exist_okare kw-only soToArgsemits them as kwargs (matching CPython).- Monty
Date - A Python
datetime.datevalue with year, month, and day components. - Monty
Date Time - A Python
datetime.datetimevalue with date, time, and optional timezone components. - Monty
Exception - Public representation of a Monty exception.
- Monty
File Handle - An open file object (the result of
open()). - Monty
Path - Owned virtual (sandbox) path carried by OS-call args.
- Monty
Time Delta - A Python
datetime.timedeltavalue representing a duration. - Monty
Time Zone - A Python
datetime.timezonefixed-offset timezone. - Open
Call Args open(path, mode)shape. The mode is parsed intoFileModebefore construction so the fs/ backend doesn’t re-parse;ToArgsre-serialises it back to aMontyObject::Stringfor the host.- Path
Bytes Data Args path + bytes datashape used byWriteBytesandAppendBytes.- Path
String Data Args path + str datashape used byWriteTextandAppendText.- Rename
Call Args rename(src, dst)shape.- Resource
Limits - Configuration for resource limits.
- Resource
Tracker - A resource tracker that enforces configurable limits.
- Stack
Frame - A single frame in a Python traceback.
- Type
Check State - Per-session type-check state: successfully committed snippets accumulate as stubs so later snippets can reference names defined by earlier ones.
- Type
Checking Config - How a type check renders whatever diagnostics it finds.
- Unicode
Error Data - Structured fields of a
UnicodeDecodeError/UnicodeEncodeError, mirroring CPython’sencoding/object/start/end/reasonexception attributes.
Enums§
- Assert
Message Annotations - Controls the pytest-style introspected
assertfailure messages ofCompileOptions::assert_message_annotations. - Builtins
Functions - Enumerates every interpreter-native Python builtin function.
- ExcData
- Structured payload attached to exception types whose CPython counterparts
carry more than a message. Currently unicode and json decode errors have
one; the enum leaves room for future variants (e.g.
OSError’serrno/filename) without another field on every exception. - ExcType
- Python exception types supported by the interpreter.
- ExtFunction
Result - Return value or exception from an external function.
- File
Mode - A parsed Python
open()mode. - Invalid
Input Error - Error returned when a
MontyObjectcannot be used as an input to code execution. - Monty
Object - An owned Python value exchanged between Monty and its host.
- Monty
Type - The Python type of a value at the host boundary — the public mirror of the
internal runtime
Typeenum. - Name
Lookup Result - Result of a name lookup from the host.
- OsFunction
Call - Tagged dispatch value for OS-level operations.
- Print
Stream - Identifies the output stream for a single print fragment.
- Print
Writer - Output handler for the
print()builtin function. - Resource
Error - Error returned when a resource limit is exceeded during execution.
- Type
Checking Format - How type-check diagnostics are rendered into text.
- Unicode
Error Object - The
objectattribute of a unicode error: the input being converted.
Constants§
- DEFAULT_
MAX_ PRINT_ COLLECT_ BYTES - Default cap for
PrintWriter::CollectString/PrintWriter::CollectStreamsand the matching Python collectors. - DEFAULT_
MAX_ RECURSION_ DEPTH - Recommended maximum recursion depth if not otherwise specified.
- LARGE_
RESULT_ THRESHOLD - Threshold in bytes above which
check_large_resultis called. - MONTY_
VERSION - The monty version this build was compiled as.
- OOM_
EXIT_ CODE - Exit code a worker uses when it exceeded its memory limit or the allocator
refused an allocation, so the parent can report
MemoryErrorinstead of an unclassifiableSIGABRT.
Statics§
- BASELINE_
MEMORY - The leanest the process has ever been at an arming point: what the worker costs to exist, before any session ran.
- LIVE_
MEMORY - Allocator-backed live bytes requested through the global allocator
Traits§
- Print
Writer Callback - Trait for custom output handling from the
print()builtin function.
Functions§
- check_
print_ collect_ limit - Rejects a collect-buffer growth that would exceed
max_bytes. - dir_
stat - Creates a
stat_resultfor a directory. - file_
stat - Creates a
stat_resultfor a regular file. - stat_
result - Creates a full
stat_resultwith all 10 fields specified. - symlink_
stat - Creates a
stat_resultfor a symbolic link. - unicode_
decode_ error_ msg - Formats the message for a
UnicodeDecodeErrorcovering the byte rangestart..end: CPython’s single-byte form (byte 0x{first_byte:02x} in position {start}) when the range is one byte, otherwise the range form (bytes in position {start}-{end - 1}).