Skip to main content
The Monty class is the main interface for creating and running a sandboxed Python interpreter. It parses Python code on initialization and can execute it multiple times with different inputs, separating parsing cost from execution.

Constructor

Create a new Monty interpreter by parsing the given code.
str
required
Python code to execute
str
default:"'main.py'"
Name used in tracebacks and error messages
list[str] | None
List of input variable names available in the code
bool
default:"False"
Whether to perform type checking on the code
str | None
Optional code to prepend before type checking, e.g. with input variable declarations or external function signatures
list[type] | None
Optional list of dataclass types to register for proper isinstance() support on output
Raises:
  • MontySyntaxError: If the code cannot be parsed
  • MontyTypingError: If type_check is True and type errors are found

Example

Methods

run()

Execute the code and return the result. The GIL is released allowing parallel execution.
dict[str, Any] | None
Dict of input variable values (must match names from constructor)
ResourceLimits | None
Optional resource limits configuration
dict[str, Callable[..., Any]] | None
Dict of external function callbacks
Callable[[Literal['stdout'], str], None] | None
Optional callback for print output
Callable[[OsFunction, tuple[Any, ...]], Any] | None
Optional callback for OS calls. Called with (function_name, args) where function_name is like 'Path.exists' and args is a tuple of arguments. Must return the appropriate value for the OS function (e.g., bool for exists(), stat_result for stat()).
The result of the last expression in the code
Raises:
  • MontyRuntimeError: If the code raises an exception during execution

Example with External Functions

Example with Resource Limits

start()

Start the code execution and return a progress object, or completion. This allows you to iteratively run code and pause/resume whenever an external function is called. The GIL is released allowing parallel execution.
dict[str, Any] | None
Dict of input variable values (must match names from constructor)
ResourceLimits | None
Optional resource limits configuration
Callable[[Literal['stdout'], str], None] | None
Optional callback for print output
  • FunctionSnapshot if an external function call is pending
  • NameLookupSnapshot if more futures need to be resolved
  • FutureSnapshot if futures need to be resolved
  • MontyComplete if execution finished without external calls
Raises:
  • MontyRuntimeError: If the code raises an exception during execution

Example with Iterative Execution

type_check()

Perform static type checking on the code. Analyzes the code for type errors without executing it. This uses a subset of Python’s type system supported by Monty.
str | None
Optional code to prepend before type checking, e.g. with input variable declarations or external function signatures
Raises:
  • MontyTypingError: If type errors are found. Use .display(format, color) on the exception to render the diagnostics in different formats.
  • RuntimeError: If the type checking infrastructure fails internally.

dump()

Serialize the Monty instance to a binary format. The serialized data can be stored and later restored with Monty.load(). This allows caching parsed code to avoid re-parsing on subsequent runs.
Bytes containing the serialized Monty instance
Raises:
  • ValueError: If serialization fails

Example

load() (static method)

Deserialize a Monty instance from binary format.
bytes
required
The serialized Monty data from dump()
list[type] | None
Optional list of dataclass types to register for proper isinstance() support on output
A new Monty instance
Raises:
  • ValueError: If deserialization fails

register_dataclass()

Register a dataclass type for proper isinstance() support on output. When a dataclass passes through Monty and is returned, it normally becomes an UnknownDataclass. By registering the original type, we can use it to instantiate a real instance of that dataclass.
type
required
The dataclass type to register
Raises:
  • TypeError: If the argument is not a dataclass type

Async Helper Function

run_monty_async()

Run a Monty script with async external functions and optional OS access. This function provides a convenient way to run Monty code that uses both async external functions and filesystem operations.
Monty
required
The Monty instance to execute
dict[str, Any] | None
Dictionary of input variable values
dict[str, Callable[..., Any]] | None
Dictionary of external functions (can be sync or async)
ResourceLimits | None
Optional resource limits configuration
Callable[[Literal['stdout'], str], None] | None
Optional callback for print output
AbstractOS | None
Optional OS access handler for filesystem operations (e.g., OSAccess instance)
The output of the Monty script

Example

MontyRepl

The MontyRepl class provides an incremental, no-replay REPL (Read-Eval-Print Loop) session. Each feed() call compiles and executes only the provided snippet against preserved heap/global state, unlike traditional REPLs that replay all history.

create() (static method)

Create a REPL session directly from source code. Returns a tuple of (repl, output) where output is the initial execution result.
str
required
Initial Python code to execute
str
default:"'main.py'"
Name used in tracebacks and error messages
list[str] | None
List of input variable names available in the code
dict[str, Any] | None
Initial input values for the session
ResourceLimits | None
Optional resource limits configuration
Callable[[Literal['stdout'], str], None] | None
Optional callback for print output
list[type] | None
Optional list of dataclass types to register
A tuple containing the REPL session and the initial execution result
Raises:
  • MontySyntaxError: If the code cannot be parsed
  • MontyRuntimeError: If the code raises an exception during execution

script_name (property)

Returns the name of the script being executed.

feed()

Execute one incremental snippet and return its output. The snippet is compiled and executed against the current session state without replaying previous code.
str
required
Python code snippet to execute
Callable[[Literal['stdout'], str], None] | None
Optional callback for print output
The result of the code snippet
Raises:
  • MontyRuntimeError: If the code raises an exception during execution

Example

dump()

Serialize the REPL session to bytes. The serialized data can be stored and later restored with MontyRepl.load().
Bytes containing the serialized REPL session

load() (static method)

Restore a REPL session from bytes.
bytes
required
The serialized REPL data from dump()
Callable[[Literal['stdout'], str], None] | None
Optional callback for print output
list[type] | None
Optional list of dataclass types to register
A new MontyRepl instance
Raises:
  • ValueError: If deserialization fails