Documentation Index Fetch the complete documentation index at: https://mintlify.com/pydantic/monty/llms.txt
Use this file to discover all available pages before exploring further.
Overview
The Monty class is the main entry point for executing sandboxed Python code in JavaScript/TypeScript. It parses Python code and provides methods to execute it with configurable inputs, external functions, and resource limits.
Constructor
new Monty ( code : string , options ?: MontyOptions )
Creates a new Monty interpreter instance by parsing the given Python code.
The Python code to parse and prepare for execution
Optional configuration for the interpreter Show MontyOptions properties
Name used in tracebacks and error messages (default: 'main.py')
Array of input variable names that can be provided at runtime
Enable static type checking on construction (default: false)
Code to prepend before type checking (e.g., type definitions)
Throws:
MontySyntaxError - If the code has syntax errors
MontyTypingError - If type checking is enabled and finds errors
Example
import { Monty } from '@pydantic/monty'
// Simple expression
const m = new Monty ( '1 + 2' )
// With inputs
const m2 = new Monty ( 'x + y' , {
inputs: [ 'x' , 'y' ],
scriptName: 'calculator.py'
})
// With type checking
const m3 = new Monty ( 'x: int = 1 \n x + 1' , {
typeCheck: true
})
Methods
run()
run ( options ?: RunOptions ): any
Executes the parsed Python code and returns the result of the last expression.
Optional execution configuration Show RunOptions properties
Values for input variables declared in the constructor
External function implementations (synchronous only - use runMontyAsync() for async)
The result of the last expression in the Python code
Throws:
MontyRuntimeError - If the code raises an exception during execution
Example:
const m = new Monty ( 'x * 2' , { inputs: [ 'x' ] })
const result = m . run ({ inputs: { x: 10 } }) // returns 20
// With external functions
const m2 = new Monty ( 'add(2, 3)' )
const result2 = m2 . run ({
externalFunctions: {
add : ( a : number , b : number ) => a + b
}
}) // returns 5
start()
start ( options ?: StartOptions ): MontySnapshot | MontyNameLookup | MontyComplete
Starts iterative execution, pausing at external function calls or name lookups. This provides fine-grained control over execution.
Same as RunOptions - optional execution configuration
result
MontySnapshot | MontyNameLookup | MontyComplete
MontySnapshot - Execution paused at an external function call
MontyNameLookup - Execution paused at an undefined name lookup
MontyComplete - Execution completed successfully
Throws:
MontyRuntimeError - If the code raises an exception
Example:
const m = new Monty ( 'a() + b()' )
let progress = m . start ()
while ( progress instanceof MontySnapshot ) {
console . log ( `Calling: ${ progress . functionName } ` )
console . log ( `Args: ${ progress . args } ` )
// Provide the return value and resume
progress = progress . resume ({ returnValue: 10 })
}
// progress is now MontyComplete
console . log ( progress . output ) // 20
typeCheck()
typeCheck ( prefixCode ?: string ): void
Performs static type checking on the code.
Optional code to prepend before type checking (e.g., type definitions)
Throws:
MontyTypingError - If type checking finds errors
Example:
const m = new Monty ( '"hello" + 1' )
try {
m . typeCheck ()
} catch ( error ) {
if ( error instanceof MontyTypingError ) {
console . log ( error . displayDiagnostics ( 'concise' ))
}
}
dump()
Serializes the Monty instance to a binary format. This allows you to save the parsed code and avoid re-parsing later.
Binary representation of the Monty instance
Example:
const m = new Monty ( 'complex_code()' )
const data = m . dump ()
// Save to file or database
fs . writeFileSync ( 'monty.bin' , data )
load() (static)
static load ( data : Buffer ): Monty
Deserializes a Monty instance from binary format.
Restored Monty instance ready to execute
Example:
const data = fs . readFileSync ( 'monty.bin' )
const m = Monty . load ( data )
const result = m . run ()
Properties
scriptName
readonly scriptName : string
Returns the script name used in tracebacks and error messages.
readonly inputs : string []
Returns the array of declared input variable names.
Helper Function: runMontyAsync()
async function runMontyAsync (
montyRunner : Monty ,
options ?: RunMontyAsyncOptions
) : Promise < any >
Helper function that runs a Monty script with support for both synchronous and asynchronous external functions.
The Monty instance to execute
Show RunMontyAsyncOptions properties
External function implementations (can be sync or async)
Resource limits to enforce
The output of the Monty script
Example:
import { Monty , runMontyAsync } from '@pydantic/monty'
const m = new Monty ( 'fetch_data(url)' , {
inputs: [ 'url' ],
})
const result = await runMontyAsync ( m , {
inputs: { url: 'https://example.com' },
externalFunctions: {
fetch_data : async ( url : string ) => {
const response = await fetch ( url )
return response . text ()
},
},
})
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.
create() (static method)
static create (
code : string ,
options ?: MontyOptions ,
startOptions ?: StartOptions
): MontyRepl
Creates a REPL session directly from source code.
Initial Python code to execute
Configuration options (scriptName, inputs, typeCheck, etc.)
Execution options for the initial code (inputs, limits)
A new REPL session instance
Throws:
MontySyntaxError - If the code has syntax errors
MontyRuntimeError - If execution fails
MontyTypingError - If type checking is enabled and finds errors
scriptName (property)
Returns the script name for this REPL session.
feed()
Executes one incremental snippet and returns its output. The snippet is compiled and executed against the current session state without replaying previous code.
Python code snippet to execute
The result of the code snippet
Throws:
MontyRuntimeError - If execution fails
Example:
import { MontyRepl } from '@pydantic/monty'
// Create REPL with initial state
const repl = MontyRepl . create ( "x = 1" )
// Feed additional snippets
const result1 = repl . feed ( "x + 10" )
console . log ( result1 )
// Output: 11
// State is preserved
const result2 = repl . feed ( "x = x * 2; x" )
console . log ( result2 )
// Output: 2
dump()
Serializes the REPL session to bytes for later restoration.
Serialized REPL session data
load() (static method)
static load ( data : Buffer ): MontyRepl
Restores a REPL session from bytes.
Serialized REPL data from dump()
Throws:
ValueError - If deserialization fails
repr()
Returns a string representation of the REPL session.