Making a Python interpreter in 1024 bytes
A Python interpreter was constructed in 1024 bytes of C code without relying on macros or libraries. The goal was to create an interpreter that produced output similar to Python, despite the limited code size. A fizzbuzz program was used as an example of what could be achieved, featuring Python-like syntax such as def, colons, indentations, and if statements without parentheses.
The interpreter was built in stages, starting with basic calculations and gradually adding more Python-like features. The CPython implementation was broken down into stages: tokenizing the source, parsing into an abstract syntax tree, analysis and optimization, bytecode emission, and bytecode interpretation. A single array held all the code and global variables.
No error handling was included, and assumptions were made about correct keywords, token boundaries, and whitespace. The parser used the C program's call stack to handle recursion. Loops were implemented by jumping backwards and reparsing the source each iteration. Functions were implemented with symbol table lookups based on single lowercase variable names.
After adding more features, the golfed version reached 1024 bytes, while the readable version exceeded 4800 bytes. The interpreter lacked error handling, support for comparison expressions, and was limited to single-character variable names. Despite being tedious, the process allowed the creation of an interpreter that functioned and resembled Python within the imposed byte limit. The code is available on GitHub for others to explore.
Written by urgent.news from Hacker News's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.
Also reported by 1 other outlet
- Making a Python interpreter in 1024 bytes austinhenley.com