Skip to main content

Crate monty_types

Crate monty_types 

Source
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 the datetime family (MontyDate, MontyDateTime, MontyTimeDelta, MontyTimeZone), DictPairs and MontyFileHandle.
  • 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 the stat_result builders hosts use to answer them.
  • ResourceTracker / ResourceLimits — the resource tracker the interpreter uses to enforce time/memory/recursion limits.
  • PrintStream / PrintWriterprint() output capture.
  • CompileOptions, ExtFunctionResult, NameLookupResult, FileMode, and the CPython-compatible formatting helpers behind their repr()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 crate
  • monty-fs — host-side filesystem mounts: maps virtual sandbox paths to real host directories.
  • monty-runtime — the monty binary: REPL, file runner, and subprocess worker mode.
  • monty-pool — an elastic pool of crash-isolated monty worker 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 behind monty’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) MontyObject pairs host callbacks consume. The #[derive(ToArgs)] macro in monty-macros emits impls of these traits via crate::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-offset timedelta reprs.

Structs§

CodeLoc
A line and column position in source code.
CompileOptions
Options controlling how Monty behavior diverges from plain CPython.
ConversionError
Error returned when a MontyObject cannot be converted to the requested Rust type.
DictPairs
A collection of key-value pairs representing Python dictionary contents.
GetenvArgs
os.getenv(key, default=None) shape. The host decides whether to substitute default when the variable is unset.
JsonErrorData
Structured fields of a json.JSONDecodeError, mirroring CPython’s msg / doc / pos / lineno / colno exception attributes.
MkdirCallArgs
mkdir(path, parents=False, exist_ok=False) shape. parents/exist_ok are kw-only so ToArgs emits them as kwargs (matching CPython).
MontyDate
A Python datetime.date value with year, month, and day components.
MontyDateTime
A Python datetime.datetime value with date, time, and optional timezone components.
MontyException
Public representation of a Monty exception.
MontyFileHandle
An open file object (the result of open()).
MontyPath
Owned virtual (sandbox) path carried by OS-call args.
MontyTimeDelta
A Python datetime.timedelta value representing a duration.
MontyTimeZone
A Python datetime.timezone fixed-offset timezone.
OpenCallArgs
open(path, mode) shape. The mode is parsed into FileMode before construction so the fs/ backend doesn’t re-parse; ToArgs re-serialises it back to a MontyObject::String for the host.
PathBytesDataArgs
path + bytes data shape used by WriteBytes and AppendBytes.
PathStringDataArgs
path + str data shape used by WriteText and AppendText.
RenameCallArgs
rename(src, dst) shape.
ResourceLimits
Configuration for resource limits.
ResourceTracker
A resource tracker that enforces configurable limits.
StackFrame
A single frame in a Python traceback.
TypeCheckState
Per-session type-check state: successfully committed snippets accumulate as stubs so later snippets can reference names defined by earlier ones.
TypeCheckingConfig
How a type check renders whatever diagnostics it finds.
UnicodeErrorData
Structured fields of a UnicodeDecodeError / UnicodeEncodeError, mirroring CPython’s encoding / object / start / end / reason exception attributes.

Enums§

AssertMessageAnnotations
Controls the pytest-style introspected assert failure messages of CompileOptions::assert_message_annotations.
BuiltinsFunctions
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’s errno/filename) without another field on every exception.
ExcType
Python exception types supported by the interpreter.
ExtFunctionResult
Return value or exception from an external function.
FileMode
A parsed Python open() mode.
InvalidInputError
Error returned when a MontyObject cannot be used as an input to code execution.
MontyObject
An owned Python value exchanged between Monty and its host.
MontyType
The Python type of a value at the host boundary — the public mirror of the internal runtime Type enum.
NameLookupResult
Result of a name lookup from the host.
OsFunctionCall
Tagged dispatch value for OS-level operations.
PrintStream
Identifies the output stream for a single print fragment.
PrintWriter
Output handler for the print() builtin function.
ResourceError
Error returned when a resource limit is exceeded during execution.
TypeCheckingFormat
How type-check diagnostics are rendered into text.
UnicodeErrorObject
The object attribute of a unicode error: the input being converted.

Constants§

DEFAULT_MAX_PRINT_COLLECT_BYTES
Default cap for PrintWriter::CollectString / PrintWriter::CollectStreams and 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_result is 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 MemoryError instead of an unclassifiable SIGABRT.

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§

PrintWriterCallback
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_result for a directory.
file_stat
Creates a stat_result for a regular file.
stat_result
Creates a full stat_result with all 10 fields specified.
symlink_stat
Creates a stat_result for a symbolic link.
unicode_decode_error_msg
Formats the message for a UnicodeDecodeError covering the byte range start..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}).