Which Standard Library Modules Are Available in Monty? A Complete Guide to the 5 Built-in Modules
Monty provides exactly five standard library modules—sys, typing, asyncio, pathlib, and os—each implemented as a minimal, sandbox-safe subset of CPython's full API.
Monty is a Python sandbox runtime developed by Pydantic that executes untrusted code in a secure environment. When working within Monty's restricted execution context, developers must know which standard library modules are available to import. This guide examines the five built-in modules implemented in the Monty source code, their specific capabilities, and how to use them effectively.
The Five Standard Library Modules Available in Monty
Monty's module system is intentionally minimal to maintain security. The available modules are registered in the BuiltinModule enum located in crates/monty/src/modules/mod.rs. When Python code executes an import statement, Monty looks up the requested name in this enum and creates the module on-demand via the create method.
sys – Interpreter Metadata and I/O Streams
The sys module provides basic interpreter metadata and placeholder objects for standard I/O streams. Implemented in crates/monty/src/modules/sys.rs, it exposes:
sys.version– Returns the Python version string (e.g.,"3.14.0 (Monty)")sys.version_info– Returns a tuple(major, minor, micro, releaselevel, serial)sys.platform– Returns"monty"sys.stdoutandsys.stderr– Placeholder objects (actual I/O is handled by the host)
import sys
print(sys.version) # "3.14.0 (Monty)"
print(sys.version_info) # (3, 14, 0, 'final', 0)
print(sys.platform) # "monty"
typing – Type Hint Markers Without Static Checking
The typing module supplies marker objects for type hints but performs no actual type checking. According to crates/monty/src/modules/typing.rs, it exports:
Any,List,Dict,Optional,Union, and other common markersTYPE_CHECKING– Constant set toFalse
Monty accepts these imports to maintain compatibility with typed codebases, but the sandbox does not enforce static types at runtime.
from typing import List, Optional, Any, TYPE_CHECKING
def process(items: List[Optional[Any]]) -> None:
pass
print(TYPE_CHECKING) # False
asyncio – Limited Coroutine Gathering
Monty's asyncio implementation is restricted to a single function. As defined in crates/monty/src/modules/asyncio.rs, only asyncio.gather(*awaitables) is available.
The host application provides the event loop implementation; Monty cannot use asyncio.run(), asyncio.create_task(), or other asyncio APIs. This design allows concurrent execution of coroutines while maintaining sandbox boundaries.
import asyncio
async def fetch(id: int, delay: float):
await asyncio.sleep(delay)
return f"Result {id}"
async def main():
results = await asyncio.gather(
fetch(1, 0.1),
fetch(2, 0.2),
)
print(results) # ['Result 1', 'Result 2']
pathlib – Object-Oriented Path Manipulation
The pathlib module exposes the Path class for filesystem path operations. Implemented in crates/monty/src/modules/pathlib.rs, this is a deliberately minimal implementation that mirrors CPython's API for constructing and inspecting paths.
It supports path joining, name extraction, suffix detection, and other pure path operations without requiring actual filesystem access (which may be restricted by the host).
from pathlib import Path
config = Path("config") / "app.json"
print(config.name) # "app.json"
print(config.suffix) # ".json"
print(config.parent) # "config"
os – Environment Variable Access
The os module currently provides only os.getenv(name) for reading host environment variables. According to crates/monty/src/modules/os.rs, this is the sole function exposed from the os namespace.
This restricted implementation allows sandboxed code to read configuration from the environment without exposing dangerous operations like os.system(), os.exec(), or file manipulation functions.
import os
api_key = os.getenv("API_KEY")
if api_key is None:
print("Warning: API_KEY not set")
else:
print("API key loaded")
How Monty Loads Standard Library Modules
Monty does not use a traditional filesystem-based import system. Instead, it maintains an internal registry of built-in modules defined in crates/monty/src/modules/mod.rs.
When Python code executes import sys or from typing import List, Monty performs the following steps:
- Lookup: The import machinery searches the
BuiltinModuleenum for a matching module name. - Creation: If found, Monty invokes the
createmethod to instantiate the module and populate its namespace with the supported attributes. - Caching: The created module is cached to handle subsequent imports efficiently.
This design ensures that only explicitly whitelisted standard library functionality is available to sandboxed code, preventing security vulnerabilities from unrestricted module access.
Summary
- Monty exposes exactly five standard library modules:
sys,typing,asyncio,pathlib, andos. - Each module is a minimal implementation designed for sandbox safety, lacking most CPython APIs.
- The
BuiltinModuleenum incrates/monty/src/modules/mod.rsregisters all available modules. - Modules are created on-demand when imported via the internal
createmethod. - Most modules support only specific functions:
asyncio.gather(),os.getenv(),sysmetadata,typingmarkers, andpathlib.Path.
Frequently Asked Questions
Can I import modules like json or re in Monty?
No. Monty only supports the five built-in modules (sys, typing, asyncio, pathlib, os). Attempting to import json, re, math, or other standard library modules will raise an ImportError because they are not registered in the BuiltinModule enum in crates/monty/src/modules/mod.rs.
Does Monty's typing module perform type checking?
No. The typing module in Monty only provides marker objects like Any, List, and Dict along with the TYPE_CHECKING constant. As implemented in crates/monty/src/modules/typing.rs, Monty does not perform static type checking or runtime type validation using these markers.
How do I run async code in Monty?
Use asyncio.gather() to run multiple coroutines concurrently. Monty's asyncio implementation in crates/monty/src/modules/asyncio.rs only supports the gather function. The host application provides the event loop, so you cannot use asyncio.run() or create tasks within the sandbox.
Is os.getenv() safe to use in Monty's sandbox?
Yes, with limitations. The os module in Monty only exposes getenv(name) to read environment variables from the host. According to crates/monty/src/modules/os.rs, it does not provide functions to modify the environment or execute system commands, maintaining the sandbox's security boundaries.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →