Skip to main content

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.
code
string
required
The Python code to parse and prepare for execution
options
MontyOptions
Optional configuration for the interpreter
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\nx + 1', { 
  typeCheck: true 
})

Methods

run()

run(options?: RunOptions): any
Executes the parsed Python code and returns the result of the last expression.
options
RunOptions
Optional execution configuration
result
any
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.
options
StartOptions
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.
prefixCode
string
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()

dump(): Buffer
Serializes the Monty instance to a binary format. This allows you to save the parsed code and avoid re-parsing later.
data
Buffer
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.
data
Buffer
required
Binary data from dump()
monty
Monty
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.

inputs

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.
montyRunner
Monty
required
The Monty instance to execute
options
RunMontyAsyncOptions
result
any
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.
code
string
required
Initial Python code to execute
options
MontyOptions
Configuration options (scriptName, inputs, typeCheck, etc.)
startOptions
StartOptions
Execution options for the initial code (inputs, limits)
repl
MontyRepl
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)

get scriptName(): string
Returns the script name for this REPL session.

feed()

feed(code: string): any
Executes one incremental snippet and returns its output. The snippet is compiled and executed against the current session state without replaying previous code.
code
string
required
Python code snippet to execute
result
any
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()

dump(): Buffer
Serializes the REPL session to bytes for later restoration.
data
Buffer
Serialized REPL session data

load() (static method)

static load(data: Buffer): MontyRepl
Restores a REPL session from bytes.
data
Buffer
required
Serialized REPL data from dump()
repl
MontyRepl
Restored REPL session
Throws:
  • ValueError - If deserialization fails

repr()

repr(): string
Returns a string representation of the REPL session.