A powerful, high-performance Python 3 Virtual Machine and Compiler engineered in pure TypeScript.
npm install @lewin671/python-vm

A high-performance Python compiler and Virtual Machine (VM) implemented entirely in TypeScript. This project aims to provide a robust, Python-compliant execution environment within the JavaScript ecosystem, featuring a complete compilation pipeline from source code to bytecode.
- Advanced Compilation Pipeline: Moves beyond simple interpretation by implementing a multi-stage pipeline: Source โ Tokens โ AST โ Control Flow Graph (CFG) โ Linear Bytecode โ VM.
- Python-Strict Semantics: Carefully implemented data structures (PyDict, PySet, PyList) that strictly follow Python's rules for equality, hashing, and numeric types (including BigInt for arbitrary-precision integers and NaN handling).
- Comprehensive Language Support:
- Core: Full support for functions, classes, closures, and decorators.
- Modern Features: Includes match statements (Structural Pattern Matching), with statements (Context Managers), and try/except/finally blocks.
- Control Flow: Robust handling of generators (yield), list/dict/set comprehensions, and nested scopes (global, nonlocal).
- Production-Ready Tooling: Includes a high-fidelity Lexer with indentation/dedentation logic, a recursive descent Parser, and a stack-based VM.
int, float, str, bool, list, tuple, dict, set, None.range, enumerate, zip, reversed, map, filter, sorted.abs, round, sum, min, max, isinstance, type, print, open, next.``bash`
npm install @lewin671/python-vm
After cloning the repository, you can run Python files directly:
`bash`
npm run build
npm start -- examples/hello.py
You can compile Python source files to a compressed binary bytecode format (.pyc) and execute them later. This avoids parsing overhead at runtime.
`bash1. Compile source to bytecode
npm start -- compile examples/hello.py hello.pyc
$3
`ts
import { PythonCompiler } from '@lewin671/python-vm';const compiler = new PythonCompiler();
// Execute code directly
const result = compiler.run(
result = [greet(x) for x in ["World", "TypeScript"]]
print(result));
// Or run a file
// compiler.runFile('./script.py');
`
Correctness is a top priority. The project includes an extensive test suite using Vitest that compares the VM output against the system's CPython interpreter for parity.
`bash``Run all tests (requires Python 3 installed locally)
npm test
This project is licensed under the MIT License - see the LICENSE file for details.