Skip to content

About

A custom interpreter for a subset of Python, built from scratch in Python. Features a lexer with INDENT/DEDENT handling, a recursive descent parser, and a tree-walking evaluator.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

PySubset Interpreter

A Python interpreter for a subset of Python, built from scratch in pure Python. No ast module. No eval(). Just hand-written lexing, parsing, and tree-walking evaluation.

CI License: MIT Python

Quick start | Feature matrix | The language | Architecture | Benchmarks | Testing | Roadmap


Overview

What An interpreter for a subset of Python. Runs scripts and drops into an interactive REPL.
Why it's interesting It handles Python's whitespace-sensitive grammar (INDENT/DEDENT tokens), classes with inheritance and super(), exception handling, f-strings, list comprehensions, and tuple unpacking, all implemented from scratch.
No shortcuts The lexer and parser are hand-written. There is no ast.parse, compile(), or eval().
Debugging Runtime errors include line numbers. Exceptions print a call-stack traceback.
Tested against CPython Every demo is executed through both CPython and the interpreter, and stdout must match.
Stack Python 3.12+ (standard library only), GitHub Actions

Feature matrix

Category Supported
Lexer Indentation (INDENT/DEDENT), comments, single-, double- and triple-quoted strings, raw strings, escape sequences, f-string literals, multi-character operators
Parser Recursive descent with operator precedence (arithmetic, comparison, boolean logic, unary)
Control flow if / elif / else, while, for, break, continue, pass
Loop else while...else, for...else (else runs when the loop exits without break)
Functions def, return, recursion, closures, default arguments, keyword arguments, *args, **kwargs, * / ** unpacking in calls, lambda defaults and *args, keyword-only parameters, decorators (stacked, with arguments), global, nonlocal
Data structures Lists, dicts, sets, tuples (including (1,)), list / dict / set comprehensions with several for and if clauses and tuple targets, lazy generator expressions
Unpacking a, b = 1, 2, a, *rest = xs, nested targets, for a, b in pairs, [*a, *b], {**a, **b}
Indexing x[0], d["key"], x[0] = 5, slicing x[1:3]
Expressions augmented assignment (+=), in / not in, is / is not, ternary, lambda, dict comprehensions, chained comparisons, short-circuit and / or, bitwise operators (`&
Statements del, chained assignment (a = b = 1), pass in class bodies
OOP class, __init__, self, class attributes, single and multiple inheritance (C3 method resolution order), cooperative super(), @property with setters, @staticmethod, @classmethod, object
Modules import m, import a.b as x, from m import x as y, from m import * (honors __all__), packages with __init__.py, cached modules with their own scope, circular imports, __name__ == "__main__", plus an allow-list of standard-library modules (math, random, json, re, collections, ...)
Generators yield, yield from (with return values), send(), throw(), close(), generator functions and methods, __iter__ written as a generator, lazy generator expressions, contextlib.contextmanager
Context managers with statements: multiple items, early return / break / continue, exception suppression via __exit__, user classes with __enter__ / __exit__, host objects such as io.StringIO and open()
Magic methods __str__, __repr__, __eq__, __hash__, ordering (__lt__ and friends), arithmetic and reflected operators (__add__, __radd__, ...), __neg__, __abs__, __bool__, __len__, __getitem__ / __setitem__ / __delitem__, __contains__, __iter__ / __next__, __call__
Exceptions try / except / else / finally, typed except ValueError as e, except (A, B), multiple except clauses, raise ValueError(...), raise X from Y, custom exception classes, bare raise, built-in exception hierarchy
Modern syntax f-strings with {expr}, format specs ({x:.2f}, {n:,}), nested specs, !r / !s, debug form {x=}; assert with optional message
Builtins print, len, range, str, int, float, bool, type, repr, input, enumerate, zip, sum, min, max, abs, sorted, reversed, any, all, map, filter, list, dict, set, tuple, round, pow, divmod, chr, ord, format, isinstance, hasattr, getattr, setattr, callable, iter, next, open, with keyword arguments such as print(sep=, end=) and sorted(key=, reverse=)
Methods String and list methods delegate to the host Python objects
Debugging Line-numbered runtime errors, call-stack tracebacks on exceptions
REPL Interactive shell with multi-line block support
CI GitHub Actions runs the smoke test and the CPython comparison on every push and PR

Quick start

Requires Python 3.12 or newer.

git clone https://github.com/shaurya-10000/python-interpreter.git
cd python-interpreter

Run a demo (tree-walking interpreter or bytecode VM):

python main.py demo/01_basics.py
python main.py --engine vm demo/01_basics.py
python main.py --dis demo/01_basics.py
python main.py --ast demo/01_basics.py

Run the comparison suite against CPython:

python tests/compare_cpython.py

Start the REPL:

python main.py

Multi-line blocks use ... continuation prompts:

>>> def add(a, b):
...     return a + b
>>> print(add(5, 5))
10
>>> exit()

The language

Variables and arithmetic

x = 10
y = 3.14
print(x + y)
print(x // 3)
print(x ** 2)

Control flow and loop else

for i in range(5):
    if i == 3:
        break
    print(i)
else:
    print("no break")      # not printed, the loop broke

n = 0
while n < 3:
    n = n + 1
else:
    print("clean exit")    # printed

Functions

def greet(name="Guest"):
    print("Hello, " + name)

greet()
greet("Alice")

def sum_all(*nums):
    total = 0
    for n in nums:
        total = total + n
    return total

print(sum_all(1, 2, 3))

Data structures and unpacking

nums = [1, 2, 3]
nums.append(4)
print(nums)

a, b = 10, 20
print(a + b)

pairs = [(1, 2), (3, 4)]
for x, y in pairs:
    print(x + y)

person = {"name": "Alice", "age": 25}
person["age"] = 26
print(person)

List comprehensions

nums = [1, 2, 3, 4, 5]
print([x * 2 for x in nums])
print([x for x in nums if x % 2 == 0])

f-strings

name = "Alice"
age = 30
print(f"Hello, {name}!")
print(f"Next year: {age + 1}")
print(f"Literal braces: {{not interpolated}}")

Object-oriented programming

class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        return self.name + " makes a sound."
    def __str__(self):
        return "Animal: " + self.name

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)
        self.breed = breed
    def speak(self):
        return self.name + " barks!"

dog = Dog("Buddy", "Labrador")
print(dog.speak())
print(dog)

Exceptions and assert

Exceptions are real classes. Standard try / except ValueError as e and raise ValueError(...) work, and you can define your own with class MyError(Exception). A shorthand also works: raise("msg") with a plain value and a bare except as e, which binds the message string.

try:
    raise("Something broke!")
except as e:
    print("Caught: " + e)

assert 1 + 1 == 2
assert 2 > 1, "math is broken"

Modules and context managers

import math
from geometry import Circle, area as circle_area
import utils.text as text

class Tracker:
    def __enter__(self):
        print("enter")
        return self
    def __exit__(self, exc_type, exc, tb):
        print("exit")
        return False

with Tracker() as t:
    print(math.sqrt(16))

See examples/modules/ for a multi-file program with a package. It is run under CPython and under this interpreter in CI, and the output must match.

Debugging

Syntax and runtime errors report the file name, line, and column, and render the offending source line with a caret (^) pointer:

Traceback (most recent call last):
  File "app.py", line 4, col 5, in greet
    return missing_var
    ^
NameError: Name 'missing_var' is not defined

Architecture

Source Code -> Lexer -> Tokens -> Parser -> AST -> Interpreter -> Output
File Responsibility
tokens.py TokenType enum and Token dataclass
lexer.py Converts source text into tokens. Tracks an indent stack for INDENT/DEDENT and ignores newlines inside brackets. Handles f-string literals.
ast_nodes.py AST node definitions for expressions and statements, with line numbers on nodes that can appear in runtime errors
parser.py Recursive descent parser that builds the AST from the token stream
environment.py Scoped variable store. Environments form a parent chain.
interpreter.py Tree-walking evaluator and call-stack tracking
runtime.py Class/instance runtime, descriptors, MRO, exceptions, context managers
builtins_env.py Built-in functions, types, and exception hierarchy
modules.py Module loader, package resolution, relative imports
generators.py Generator runtime (yield, yield from, send, throw, close)
diagnostics.py Column-level tracebacks and source-snippet rendering
opcodes.py Bytecode instruction set, CodeObject, and disassembler
compiler.py AST-to-bytecode compiler with static scope resolution and constant folding
vm.py Stack-based bytecode VM with exception tables and frame-suspended generators
main.py CLI entry point and REPL with multi-line buffering
demo/ Numbered demo scripts covering each feature area
tests/compare_cpython.py Runs each demo through CPython and the interpreter and compares stdout
tests/test_basic.py Smoke test run by CI
.github/workflows/ci.yml GitHub Actions workflow

Design principles

  1. The lexer owns whitespace. INDENT and DEDENT are emitted by the lexer, so the parser sees explicit block boundaries.
  2. The parser owns precedence. Precedence is encoded as nested functions (_or, _and, _not, _comparison, _addition, and so on).
  3. The interpreter owns scoping. Each environment has a parent pointer and get walks up the chain. Function calls create a new environment; while and if blocks share the enclosing one.
  4. The interpreter is a visitor. _eval_statement and _eval_expr dispatch on node type, so a new node means a new case.
  5. Errors carry context. Expression nodes carry a line, and statement evaluation attaches it to errors. The call stack is snapshotted onto the exception before unwinding, so tracebacks can be rendered after the stack is empty.

Benchmarks

Benchmark: fib(25), timed in-process so Python startup time is excluded.

Benchmark CPython 3.12 Tree-Walker Bytecode VM
fib(25) ~6.5 ms ~1,189 ms ~2,373 ms
sum_loop(10000) ~0.5 ms ~9.4 ms ~47.9 ms
generators(1000) ~0.14 ms ~52.0 ms ~14.9 ms (3.5x faster than tree)

That gap is expected for a tree-walking interpreter written in Python: it is an interpreter running on top of another interpreter. Timing whole processes (for example with Measure-Command) hides the gap, because interpreter startup dominates CPython's run.

Ideas for future work:

  • Compile the AST to bytecode and run it on a stack VM (the biggest expected speedup)
  • Cache variable lookups instead of walking the scope chain
  • Constant folding at parse time

Testing

The comparison harness is the main test suite. It discovers every file in demo/, executes it through CPython and through the interpreter, and requires identical stdout. Demos that use this language's own exception syntax are translated to standard Python for the CPython side.

python tests/compare_cpython.py

CI runs the smoke test and the comparison on every push and pull request:

python -m unittest tests/test_unit.py -v
python main.py tests/test_basic.py
python tests/compare_cpython.py
python tests/compare_examples.py

The workflow is defined in .github/workflows/ci.yml.

Known differences from CPython

  • Shorthand exceptions. raise("msg") with a plain value and a bare except as e still work and bind e to the message string. Built-in runtime errors (such as division by zero) are mapped to the matching exception class by name.
  • Only a subset of Python is implemented. See the feature matrix.
  • Generators run on helper threads. Each started generator parks one thread until it finishes, so a generator abandoned half-way keeps its thread until the program exits, and its finally block does not run when it is garbage collected (call close() to run it). Each yield costs a thread handoff, which makes generators much slower than ordinary calls.
  • Only contextlib.contextmanager is supported from contextlib.
  • Only an allow-list of standard-library modules can be imported. os and sys are deliberately not available.
  • Errors inside imported modules include the module file name, line, column, and source snippet. Relative imports (from . import x) are supported.

Project structure

python-interpreter/
|-- .github/workflows/ci.yml    GitHub Actions CI
|-- demo/                       Numbered demo scripts (feature coverage)
|-- examples/modules/           Multi-file import example, compared with CPython in CI
|-- tests/
|   |-- compare_cpython.py      Runs demos on CPython and PySubset, diffs stdout
|   |-- test_basic.py           CI smoke test
|-- tokens.py                   TokenType enum and Token dataclass
|-- lexer.py                    Source to tokens (INDENT/DEDENT, f-strings)
|-- ast_nodes.py                AST node dataclasses with line numbers
|-- parser.py                   Tokens to AST (recursive descent)
|-- environment.py              Scoped variable store
|-- interpreter.py              AST evaluation and class runtime
|-- main.py                     CLI entry point and REPL
|-- benchmark.py                Fibonacci benchmark
|-- README.md
|-- LICENSE

What I learned

  • Lexing is harder than it looks. The lexer must track an indent stack, emit INDENT/DEDENT tokens, and skip blank lines and comments without breaking indentation state. F-strings add a second lexical mode (string literal vs. interpolated expression).
  • Parser precedence lives in function ordering. The difference between 2 + 3 * 4 and 2 * 3 + 4 comes from the order of the recursive descent functions.
  • Scoping is the hidden complexity. while loops must not create a new scope, but function calls must. My early while loop froze because each iteration created a fresh environment that never saw the updated counter.
  • Magic methods are lookups, not hooks. print(obj) showed the wrong output because the print builtin called Python's raw print(). It had to resolve obj.__str__ first.
  • Exceptions are control flow. return, break, and continue are implemented as internal exceptions that unwind the call stack. A try handler must re-raise them, or it silently swallows the return.
  • Tracebacks need a snapshot before unwinding. The finally: stack.pop() runs before the exception reaches the top, so the stack is empty by the time you want to print it. The fix is to attach a snapshot to the exception object.
  • Test against a reference implementation. Running the same programs through CPython found a real bug (and / or returned booleans instead of operands) that hand-written expected outputs would not have caught.

Roadmap

  • Bytecode VM
  • Column-level error positions and source-snippet rendering

License

Released under the MIT license. See LICENSE.

About

A custom interpreter for a subset of Python, built from scratch in Python. Features a lexer with INDENT/DEDENT handling, a recursive descent parser, and a tree-walking evaluator.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages