Back
A Python interpreter that fits in 1024 bytes of C
SiTech AI Team3 წთ. საკითხავი

A Python interpreter that fits in 1024 bytes of C

Austin Henley squeezed a working Python interpreter into 1024 bytes of C: nested loops, functions and fizzbuzz, with no AST, no bytecode and no error handling at all.

Most of Austin Henley's weekend projects are an excuse to write software by hand, and his latest one came with a tight budget: a Python interpreter in C that fits in 512 bytes of source. The target turned out to be out of reach — in his words, his code golf skills were not up to snuff — so he settled on 1024 bytes instead, with no macro tricks and no libraries doing the heavy lifting.

The test program was a fizzbuzz that looks distinctly like Python: a def, colons, indentation, and no parentheses around the condition of an if. Only a subset of the language fits, and the rules are strict.

What the interpreter does, and what it refuses to do

There is no error handling of any kind; the interpreter assumes keywords are spelled correctly and that token boundaries are right. It strips most whitespace as it reads the program, keeping only indentation and the spaces inside string literals. Variables and function names are limited to a single lowercase character, which lets symbol table lookups be a direct array index rather than a search. State lives in a handful of globals: a 999-byte source buffer, a 256-slot symbol table and a few position markers.

Execution without an abstract syntax tree

The design has almost nothing in common with CPython, which tokenises, parses to an abstract syntax tree, analyses, compiles to bytecode and only then interprets. Henley's version parses with recursive descent and executes expressions as it goes; a block returns when indentation decreases, so the C call stack handles nesting. Nothing is compiled, so loops work by jumping backwards and reparsing the source on every iteration, remembering where the condition starts. Function calls save the caller's position, jump into the body, and restore it at the end.

How it got down to 1024 bytes

Reaching that size from a readable version, which runs past 4800 bytes, took ordinary golfing: shorter names, dropped optional braces, and tricks from an old Stack Overflow thread on golfing in C, including GNU C89 quirks. A four-argument parser function became a one-liner that uses ASCII arithmetic to work out which operator it is reading; a recursive helper for skipping to the end of a line ended up as Y(){c&&c-10&&Y(G());}, testing for zero and newline by subtraction. Comparison expressions were next on the chopping block — truthiness keeps if n%15: working — and Henley estimates that a fizzbuzz-only build could come in under 800 bytes. Both versions are on GitHub.

SSiTech

SiTech — AI-powered web development

We build fast, modern websites and bring AI into real business workflows. Have a project or a question? We'd love to help.