ls lib/python-in-c/
Building a Python in C
We write minipy, an interpreter for a subset of Python, in C: from an empty file to a bytecode VM with reference counting and a cycle collector, each piece set beside the way CPython 3.15 does it.
This course is for readers who know Python well and can read C: pointers,
structs, malloc. We build minipy, an interpreter for a subset of Python,
one piece per lesson, and after each piece we read how CPython 3.15 does the
same job, in its source at tag v3.15.2. The code for every lesson is in the
minipy repository, tagged per
lesson: C11 and a Makefile, tested with Apple clang on macOS.
minipy will run ints of any size, floats, strings, lists, tuples, dicts, functions with closures, classes with single inheritance, exceptions and generators. It will leave out imports of Python modules, async, f-strings and bytes, multiple inheritance, threads and a JIT. Where it differs from CPython on code they both accept, the lesson says so.
Reading source
- 01 Tokens, and how Python counts indentation draftSource text to tokens, and the indentation stack that turns leading spaces into INDENT and DEDENT.
- 02 Parsing expressions by precedence climbing draftRecursive descent for operators of different strengths, and the first AST nodes as tagged unions in C.
- 03 Statements and blocks draftParsing assignment, if, while and def, with INDENT and DEDENT standing where other languages put braces.
- 04 How CPython parses: a PEG grammar draftSince 3.9 CPython's parser is generated from Grammar/python.gram. What a PEG parser does that ours does not.
- 05 A first evaluator: walking the tree plannedRun the AST directly, with C integers as the only values: enough for loops, conditions and print.
Objects
- 06 Everything is an object plannedThe object header, a reference count and a type pointer, and why a type is an object too.
- 07 Operators through type slots plannedHow a + b finds the code to run: function pointers on the type, like CPython's tp_ and nb_ slots.
- 08 Integers of any size, and floats plannedInts as arrays of digits (30 bits each in CPython's default build), and floats as C doubles.
- 09 Strings plannedImmutable text with a cached hash, and CPython's choice of one, two or four bytes per character.
- 10 Lists and tuples plannedA growable array that over-allocates, and a fixed one.
- 11 Dicts: a hash table that keeps order plannedOpen addressing over a small index table and a dense array of entries, the layout CPython has used since 3.6.
- 12 The evaluator, on objects plannedThe tree-walker again, now with every value a pointer to an object.
Memory
- 13 Reference counting plannedWho owns a reference, when to increment, when to decrement, and what happens at zero.
- 14 Finding reference counting bugs plannedLeaks and use-after-free, caught by a debug mode that counts live references and by AddressSanitizer.
- 15 What reference counting cannot free plannedA list that contains itself, and why its count never reaches zero.
- 16 A cycle collector plannedFind unreachable cycles by subtracting the references objects hold to each other, as CPython's gc does with gc_refs.
- 17 Generations plannedCollect young objects often and old ones rarely. CPython 3.14.0 to 3.14.4 shipped an incremental collector; 3.14.5 and 3.15 went back to generations.
- 18 Small ints, interning and immortal objects plannedObjects made once and shared: CPython 3.15 preallocates the ints from -5 to 1024, interns strings, and since 3.12 has objects it never counts.
- 19 A small-object allocator plannedPools and arenas for the many small blocks an interpreter asks for, after CPython's obmalloc.
Bytecode
- 20 From trees to bytecode plannedWhy interpreters compile to a flat list of instructions, and the instruction set of a stack machine.
- 21 The compiler plannedExpressions, assignments, jumps for if and while, and a code object to hold the result.
- 22 The evaluation loop plannedA loop over instructions with a value stack. CPython generates its loop from Python/bytecodes.c.
- 23 Functions, frames and calls plannedA frame per call, arguments on the stack, and returning a value.
- 24 Scopes: locals, globals, builtins plannedA symbol table decides where each name lives before any code runs.
- 25 Closures and cells plannedVariables that outlive the call that made them.
- 26 Exceptions plannedRaising and unwinding, and the exception table CPython has used since 3.11, which costs nothing until something is raised.
- 27 Generators plannedA frame that stops in the middle and resumes: yield, send and the generator object.
- 28 Classes and instances plannedA class is an object that makes objects. minipy keeps instance attributes in a dict; CPython does something more compact.
- 29 Attribute lookup plannedThe method resolution order, descriptors and bound methods: what obj.name does.
The C boundary and speed
- 30 The C API boundary plannedBuiltin functions written in C, and what CPython's C API promises extension modules.
- 31 Dispatch: switch, computed gotos, tail calls plannedHow the loop gets to the next instruction. CPython uses computed gotos where the compiler allows, and 3.14 added an opt-in tail-calling interpreter.
- 32 Inline caches and specialization plannedRewriting instructions at run time for the types they meet, as CPython has done since 3.11, in a small version for minipy.
- 33 minipy against CPython plannedMeasuring both on the same programs, and what accounts for the difference.