


















































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



















































Before you write a single line of Python, you need to understand the machine you're commanding. Every variable you create, every function you call, every import you type eventually turns into electricity moving through silicon. This module builds that foundation from the ground up: transistors → logic gates → the CPU → memory → the operating system. Nothing here is "optional background" — it is the physical reality that every later module (especially Modules 1 – 3, where we open up CPython's internals) rests on.
Imagine a massive wall of light switches in a warehouse. Each switch can only be in one of two positions: ON or OFF. You can't set a switch to "sort of on." That's it — two states, no in-between.
Now imagine you wire groups of these switches together so that flipping certain switches automatically forces others into a particular position, based on simple rules like "only turn the output switch ON if both input switches are ON." Congratulations — you've just built a logic gate using light switches instead of electricity. A modern CPU is, at its core, billions of these switches (transistors), wired into groups (logic gates), wired into bigger groups (circuits), that together can add numbers, compare values, and move data around — all by turning switches on and off, billions of times per second.
Transistor: A tiny electronic switch, built from a semiconductor material (usually silicon — an element that can act as either a conductor of electricity or an insulator, depending on how it's treated). A transistor has three connections: a gate, a source, and a drain. Applying voltage to the gate lets current flow from source to drain (switch "ON"); no voltage means no current flows (switch "OFF"). Modern CPUs contain billions of these, each smaller than a virus.
Binary representation: A number system with only two digits, 0 and 1 (as opposed to our normal decimal system, which has ten digits, 0–9). Computers use binary because a transistor only has two reliable states (on/off), so 1 naturally represents "on" and 0 represents "off."
Bit (short for "binary digit"): The smallest unit of data a computer can store — a single 0 or a single 1. One bit is one transistor's worth of information (electrically), or a single yes/no answer.
Byte: A group of 8 bits. A byte can represent 2^8 = 256 different values (0 through 255 in decimal). Bytes are the standard "chunk size" computers use to address and move data — memory is measured and addressed byte-by-byte, not bit-by-bit.
Two's complement arithmetic: The standard method computers use to represent negative numbers in binary. Instead of a separate "sign bit" bolted onto a positive number (which causes ugly edge cases like "positive zero" vs "negative zero"), two's complement flips all the bits of a positive number and adds 1 to represent its negative. Example with a 4-
bit number: 0011 is +3. Flip all bits: 1100. Add 1: 1101. So 1101 represents −3. This trick lets the CPU use the exact same addition circuitry for both addition and subtraction — a huge simplification in hardware design.
Logic gate: A physical circuit built from a handful of transistors that implements one basic logical operation:
AND gate: output is 1 only if both inputs are 1. OR gate: output is 1 if at least one input is 1. NOT gate (inverter): flips a single input (0 → 1, 1 → 0). XOR gate (exclusive or): output is 1 if the inputs are different from each other.
These four gates, combined in different patterns, are enough to build every operation a computer performs — from addition to running a Python interpreter.
CPU registers: Extremely small, extremely fast storage locations built directly into the CPU chip itself (not in RAM, which is comparatively far away and slow). A modern CPU might have only a few dozen registers, each holding a single value (like 64 bits). Registers are where the CPU actually performs its work — before the CPU can add two numbers, it must first load both numbers into registers.
ALU (Arithmetic Logic Unit): The part of the CPU that actually performs math (addition, subtraction, multiplication) and logical comparisons (is this value greater than that one? are they equal?). It's built entirely from the logic gates described above — a physical circuit, not "code." When you write x + y in Python, at the very bottom of a long chain of translation, the ALU is what actually computes the sum.
Instruction: A single, tiny command the CPU knows how to execute, such as "add these two register values" or "load this value from memory into a register." Programs — no matter what language they're written in — are ultimately broken down into long sequences of these instructions.
Fetch-Decode-Execute cycle: The repeating three-step loop every CPU runs, billions of times per second, for every single instruction:
After execute, the program counter advances to the next instruction, and the cycle repeats. This loop is the literal heartbeat of every computer, from a smart thermostat to a supercomputer.
You haven't installed Python yet in this module — this is about the physical machine, so let's trace through what happens electrically when a CPU adds two small numbers, 3 + 5 , at the hardware level (conceptually — this is not Python code, it's a trace of CPU behavior):
Step 1 (FETCH): The CPU's program counter register points to memory address 0x1000. The CPU reads the instruction stored there: "LOAD register R1 with value 3"
Step 2 (DECODE):
(This exercise proves to yourself that two's complement lets addition circuitry handle subtraction for free — no special "subtract" hardware needed.)
0.2 Memory Hierarchy & Caches
Imagine you're a chef in a busy kitchen. You don't walk to the grocery store (slow) every time you need an onion. Instead:
The onion you're currently holding and cutting is like a CPU register — instantly available, but you can only hold a couple of items at once. The cutting board and nearby prep counter are like cache — a small stash of ingredients you grabbed recently because you expect to need them again soon (fast to reach, but limited space). The kitchen's walk-in fridge is like RAM (main memory) — much bigger than the counter, holds everything you need for today's service, but takes a few extra steps to walk over and open the door. The grocery store across town is like disk storage (SSD/hard drive) — enormous capacity, but painfully slow compared to reaching for something on your counter.
The entire design philosophy of computer memory is: keep the most likely to be needed next data as physically close to the CPU as possible, because closer means faster, but closer also means smaller and more expensive per byte.
Memory hierarchy: The layered arrangement of storage types in a computer, ordered from smallest/fastest/most expensive (CPU registers) to largest/slowest/cheapest (disk storage), with cache and RAM in between. Every layer exists purely as a speed-vs-capacity trade-off; there's no single memory technology that is both huge and instant, so engineers stack several.
SRAM (Static RAM): The memory technology used to build CPU caches. It's built from a small cluster of transistors (typically 6) per bit, which hold their value as long as power is supplied, with no need for refreshing. It's extremely fast but expensive and takes up more physical space per bit — which is why CPUs only have a few megabytes of it.
DRAM (Dynamic RAM): The memory technology used for main system RAM (the sticks you might install in a desktop computer). Each bit is stored using a single transistor and a tiny capacitor (a component that holds an electrical charge). Capacitors leak charge over time, so DRAM must be "refreshed" (re-written) thousands of times per second to avoid losing data. This refresh overhead, plus the physical distance from the CPU, makes DRAM significantly slower than SRAM cache — but it's far cheaper per byte, so we can afford gigabytes of it.
Cache: A small amount of very fast SRAM memory sitting physically close to (or on) the CPU chip, which stores copies of data recently read from — or about to be needed from — the slower main RAM. Its entire purpose is to reduce the number of times the CPU has to make a slow trip out to RAM.
L1, L2, L3 cache: The CPU cache is itself layered, exactly like the broader memory hierarchy:
L1 cache: Smallest (often 32–64 KB) and fastest, usually split into separate sections for instructions and data, built directly into each CPU core. L2 cache: Larger (often 256KB–1MB) and slightly slower, usually private to each core. L3 cache: Largest (several MB to tens of MB) and slowest of the three, usually shared across all CPU cores on the chip. The CPU checks L1 first; if the data isn't there ("miss"), it checks L2, then L3, then finally falls back to RAM.
Cache line: The smallest unit of data the cache moves at a time — typically 64 bytes. Even if your program only asked for a single 4-byte integer, the CPU pulls in the entire 64-byte cache line surrounding it, betting that you'll want the nearby data soon too.
Cache locality: The principle that programs tend to access memory in predictable patterns, which caches exploit:
Spatial locality: If you access one memory address, you're likely to access nearby addresses soon (e.g., looping through consecutive elements of an array). This is exactly why cache lines fetch 64-byte chunks instead of single bytes. Temporal locality: If you access a memory address, you're likely to access that same address again soon (e.g., a loop counter variable that gets read and updated every iteration).
Cache miss: What happens when the CPU looks for data in the cache and doesn't find it, forcing a slower trip to a lower cache level or all the way to RAM. A "cache hit" is the opposite — the data was already there. Programs with poor locality (jumping around memory unpredictably) suffer many more cache misses, and can run dramatically slower than programs with the exact same number of instructions but better memory access patterns.
Virtual memory: A system where each running program is given the illusion that it has access to a huge, private, contiguous block of memory addresses — even though physically, RAM is shared among many programs and may be fragmented, and some of that "memory" might not even be in RAM right now (it could be swapped out to disk). The operating system and CPU work together to maintain this illusion.
Physical vs. virtual addresses: A virtual address is the memory address a running program believes it's using — clean, private, and starting conceptually from a predictable layout. A physical address is the actual location in the physical RAM chips where that data really lives. The mapping between virtual and physical addresses is maintained by the operating system and hardware, and can change over time (e.g., when memory is moved or swapped to disk) without the program ever knowing.
Page Table: A data structure, maintained by the operating system, that stores the mapping from virtual addresses to physical addresses, organized in fixed-size chunks called "pages" (commonly 4 KB each). Every time a program accesses memory, this table must be consulted to translate the virtual address it used into the real physical address.
TLB (Translation Lookaside Buffer): A small, extremely fast cache — built into the CPU itself — that stores recently- used virtual-to-physical address translations, so the CPU doesn't have to walk through the full page table (a relatively slow, multi-step lookup) on every single memory access. A "TLB miss" forces the slower full page-table walk.
Let's trace what happens, at a memory-access level, when a simplified program sums the elements of an array in a tight loop (again, this is a conceptual hardware trace, not Python yet — we'll write real Python starting in Module 1):
Program: sum the 4 integers stored consecutively starting at virtual address 0x
Step 1: CPU wants to read the value at virtual address 0x2000.
Think of a busy airport. Individual airlines (regular programs) aren't allowed to just walk onto the runway and land their own planes whenever they want — chaos and collisions would follow. Instead, air traffic control (the OS kernel) has exclusive authority over the runways (hardware: disk, network, memory), and every airline must request permission and wait for controlled instructions.
When your program wants to read a file, send a network packet, or allocate memory, it can't touch the hardware directly. It has to ask air traffic control (the kernel) to do it on the program's behalf, through a strictly defined communication channel — a system call.
Operating system kernel: The core piece of software that has full, privileged control over the computer's hardware (CPU, memory, disk, network devices). It runs "underneath" every other program and enforces the rules that let multiple programs share one machine safely.
User space: The restricted execution mode where ordinary programs (your Python scripts, your web browser, your text editor) run. Programs in user space cannot directly touch hardware or other programs' memory — the CPU itself enforces this restriction at a hardware level.
Kernel space: The privileged execution mode where the OS kernel runs, with full access to hardware and memory. Only trusted, carefully-audited kernel code runs here, because a bug here can crash or compromise the entire machine, not just one program.
System call (syscall): The formal, controlled "doorway" through which a user-space program requests a kernel-space service — e.g., "open this file," "send this network data," "give me more memory." The CPU has special instructions (and hardware support) to safely switch from user space to kernel space, execute the privileged operation, and switch back — without letting the user program sneak in unauthorized instructions along the way. Every time your Python program opens a file ( open("data.txt") ), several system calls happen behind the scenes.
Process: A running instance of a program, along with everything it needs to run independently: its own private virtual memory space, its own set of open files, and its own execution state. Two processes cannot (normally) see or corrupt each other's memory — the OS and hardware enforce this isolation.
PCB (Process Control Block): A data structure the kernel maintains for every process, storing everything the kernel needs to manage it: the process ID, its current state (running/waiting/etc.), saved register values, memory mappings, and open file handles. When the CPU switches from running one process to another, it's the PCB that lets the kernel save exactly where the old process left off, and restore exactly where the new one should resume.
Context switching: The act of the CPU pausing one process (saving its register values and state into its PCB) and resuming another (loading that other process's saved state from its PCB). This is how a CPU with, say, 8 physical cores can appear to run dozens or hundreds of processes "simultaneously" — it's rapidly switching between them, often dozens of times per second, faster than a human can perceive.
Scheduling algorithm: The kernel's policy for deciding which process gets to run next, and for how long, when there are more runnable processes than CPU cores available. Different algorithms optimize for different goals (e.g., fairness, responsiveness for interactive programs, throughput for batch jobs) — examples include round-robin (each process gets a fixed time slice, in turn) and priority-based scheduling.
POSIX Threads (pthreads): A standardized library/API (Application Programming Interface — a defined set of functions other programs can call) for creating and managing threads: independent sequences of execution that live inside a single process and share that process's memory (unlike processes, which have separate, isolated memory). Threads
are "lighter weight" than processes because creating one doesn't require setting up a whole new isolated memory space.
Kernel-level thread mapping: How the OS kernel keeps track of and schedules threads. In most modern systems, each thread you create is directly visible to and scheduled by the kernel (as opposed to older models where a language runtime managed many threads on top of just one kernel-visible thread).
CPU affinity: The ability to "pin" a specific process or thread to run only on a specific CPU core (or set of cores), rather than letting the scheduler freely move it between cores. This can improve cache performance (Module 0.2) since a "sticky" thread keeps reusing the same core's warm cache, instead of having its cached data go cold every time it's rescheduled onto a different core.
Multiprocessing interlocks: General term for the synchronization mechanisms (like locks) that prevent multiple processes or threads from corrupting shared data by accessing/modifying it at the exact same time. We'll go into full technical depth on this in Module 6.
Let's trace, conceptually, what happens when a program executes something as simple as printing text to the screen — an operation that requires the kernel because "the screen" is a hardware device the program isn't allowed to touch directly:
Step 1: The user-space program (running with restricted CPU privileges) prepares the text "Hello" and wants it displayed.
Step 2: The program cannot write directly to the screen hardware — it has no privilege to do so. Instead, it executes a special CPU instruction that triggers a "trap" (a controlled interrupt), requesting a system call — specifically, something like "write" — and specifies: which file/device (the terminal), what data ("Hello"), how much (5 bytes).
Step 3: The CPU hardware switches execution mode from user space to kernel space. This is not optional or bypassable by the program — it's enforced at the hardware level.
Step 4: The kernel's "write" system call handler runs (now with full privileges). It validates the request, locates the terminal device driver, and instructs the hardware to actually display the characters.
Step 5: The kernel switches the CPU back to user space, and the program's execution resumes exactly where it left off — as if nothing happened, except now "Hello" is visible on screen.
This entire round-trip (user space → kernel space → user space) happens for almost every interaction your program has with the outside world: reading input, writing files, sending network requests, even asking "what time is it?" It's invisible to you as a Python programmer, but it's happening underneath every print() , every open() , every requests.get().
Assuming a program "directly" writes to a file or the screen: In reality, every such interaction is mediated by a system call and the kernel. Understanding this helps explain why file/network operations are relatively "expensive"
Term One-Line Definition
Spatial/temporal locality Programs tend to reuse nearby/same memory soon
Virtual memory Illusion of private, contiguous memory per program
Page table OS structure mapping virtual to physical addresses
TLB CPU cache for virtual-to-physical address translations
Kernel Privileged core OS software controlling hardware
User space / kernel space Restricted vs. privileged CPU execution modes
System call Controlled request from user space into kernel space
Process Independent running program with isolated memory
Thread Lightweight execution unit sharing memory within a process
Context switch CPU pausing one process/thread and resuming another
End of Module 0. Module 1 begins turning this hardware foundation into the CPython compilation pipeline — how your .py source file becomes something this hardware can actually execute.
In Module 0 you learned that a CPU only understands raw binary instructions, executed one Fetch-Decode-Execute cycle at a time. But you're going to write Python — readable text like x = 3 + 5. This module answers the question: how does human-readable Python source code become something the machine in Module 0 can actually run?
The answer is CPython (the standard, official implementation of Python, written in the C programming language — when people say "Python," they almost always mean "CPython" running their code). CPython does not translate your .py file directly into raw CPU instructions ahead of time, the way C compilers do. Instead, it goes through several intermediate stages, and the final stage is interpreted by a virtual machine — a program that pretends to be a CPU, but whose "instructions" are Python-specific. This module walks through that entire pipeline, stage by stage.
Imagine you're an editor reviewing a manuscript, but you don't care about the exact words the author chose — you care about the structure of the story: which sentences form which paragraphs, which paragraphs form which chapters, and how it all nests together. You'd take the raw manuscript (a long stream of text) and redraw it as an outline: Chapter 1 → Section 1.1 → Paragraph A → Sentence 1, Sentence 2 → Paragraph B, and so on.
That's exactly what the first stage of CPython does to your source code. It takes the raw text of your .py file and converts it into a tree-shaped outline of what your program actually means structurally — this if contains this print , this function contains this loop, this loop contains this expression — stripped of the superficial details like extra spaces or which line a statement was written on.
Lexical analysis (tokenizing): The very first processing step. Before CPython can understand structure, it has to break the raw stream of characters in your source file into meaningful "words" called tokens — e.g., the text x = 3 + 5 gets broken into the tokens NAME(x) , OP(=) , NUMBER(3) , OP(+) , NUMBER(5) , NEWLINE. This is handled by CPython's internal tokenizer logic (historically implemented in a file called tokenizer.c in the CPython source code — C is the language CPython itself is written in).
Token: A single, indivisible unit of meaning identified during tokenizing — a keyword ( if , def , for ), an identifier/name ( x , my_function ), a literal value ( 3 , "hello" ), an operator ( + , == ), or punctuation ( : , ( , ) ). Tokens are the "words" that the next stage assembles into "sentences."
Token stream: The full ordered sequence of tokens produced by tokenizing an entire source file — essentially your program, translated from raw characters into a clean list of meaningful pieces, still entirely linear (not yet structured into a tree).
Grammar / Context-Free Grammar (CFG): A formal set of rules that defines what sequences of tokens count as "valid Python." For example, a grammar rule might say: "an if_statement consists of the keyword if , followed by an
Assign( targets=[ Name(id='x', ctx=Store())], value=BinOp( left=Constant(value=3), op=Add(), right=Constant(value=5)))], type_ignores=[])
Let's walk through exactly what each layer means:
Module : The root node. Every Python file, when parsed, becomes a Module node — it represents "the whole program," and its body is a list of the top-level statements inside it. Assign : The single statement in our program ( x = 3 + 5 ) is an assignment statement. An Assign node always has targets (what's being assigned to — a list, because Python allows multiple targets like a = b = 5 ) and value (what's being assigned). Name(id='x', ctx=Store()) : This represents the variable name x. Notice ctx=Store() — this tells CPython that in this particular usage, the name x is being written to (stored), not read. If we had written print(x) instead, the AST would show ctx=Load() for that occurrence of x , since we're reading its value there. This Store/Load distinction is critical — it's how CPython later knows whether to generate a "save this value" instruction or a "fetch this value" instruction. BinOp : Represents a binary operation — anything with a left operand, an operator, and a right operand. Constant(value=3) and Constant(value=5) : The literal numbers, stored directly as constant values in the tree. Add() : The specific operator node representing +. Notice it's not stored as the string "+" — it's its own distinct node type. This matters because CPython later needs to decide which bytecode instruction (Module 1.2) to emit, and having a dedicated Add node type (versus Sub , Mult , etc.) makes that decision a simple lookup rather than string comparison.
Notice something important: nowhere in this tree do you see the number of spaces we used, or the fact that we could have written x=3+5 (no spaces) and gotten the exact same tree. That's the "abstract" part of Abstract Syntax Tree — surface formatting is discarded; only meaning survives.
Confusing SyntaxError with NameError / TypeError : A SyntaxError happens during parsing — before your program ever runs — because the token stream didn't match any valid grammar rule (e.g., a missing colon, mismatched parentheses). A NameError or TypeError happens during execution, long after parsing succeeded, because the meaning of an otherwise-valid program turned out to be invalid (e.g., using a variable that was never defined). Beginners often assume all errors are "the same kind" of mistake; they are caught at entirely different pipeline stages. Believing indentation is "cosmetic" in Python: Unlike most languages, in Python, indentation is part of the grammar — it determines block structure (which statements belong inside an if , a for , a function). The tokenizer actually emits special INDENT and DEDENT tokens based on whitespace changes, which the parser then uses structurally. This is why inconsistent indentation causes a real parsing failure ( IndentationError ), not just an ugly-looking file. Assuming comments and whitespace survive into the AST: They don't. If you're ever inspecting or generating an AST (as we will in Module 5.3), remember it has no concept of comments — they're discarded during tokenizing and never reach the tree at all.
Thinking parsing is slow or "the bottleneck": For typical scripts, parsing is extremely fast compared to actually running the code. Beginners sometimes worry about "compilation overhead" when the real performance costs (covered starting in Module 1.3) lie elsewhere.
Using the ast module as shown above:
1.2 Bytecode Generation & The Code Object
Think back to the editor's outline analogy from 1.1. Now imagine that outline needs to be handed to a stage director, who must convert "Chapter 1 → Scene A → Character enters, says line" into a literal, numbered list of cues for the stage crew: "Cue 1: raise the lights. Cue 2: open the curtain. Cue 3: play sound effect." That flattened, numbered, step- by-step cue sheet — derived from the tree-shaped outline, but now a simple linear sequence — is exactly what bytecode is. CPython takes the tree-shaped AST and "flattens" it into a linear list of simple, numbered instructions that a much simpler machine (the CPython Virtual Machine, covered in 1.3) can execute one at a time.
Control Flow Graph (CFG): An intermediate representation, built from the AST, that maps out every possible path execution could take through a piece of code — including branches ( if / else ), loops, and jumps. Nodes in this graph represent straight-line blocks of instructions with no branching; edges represent the possible jumps between them (e.g., "if the condition is false, jump to the else block"). CPython's compiler builds something conceptually like this internally as a step toward generating linear bytecode that correctly implements all the branching logic that was expressed as nested tree structure in the AST.
Bytecode compilation: The overall process (handled internally by CPython's compiler, historically centered around a file called compile.c ) of walking the AST and emitting a flat sequence of low-level instructions — bytecode — that captures the exact same behavior as the tree, but in linear, step-by-step form. This is fundamentally different from a traditional compiler like GCC compiling C into native machine code: CPython's bytecode is not real CPU instructions. It's a custom instruction set understood only by CPython's own virtual machine (1.3) — this is what makes Python "interpreted" rather than "compiled" in the traditional sense, even though a real compilation step does happen internally.
Bytecode: The actual output of this compilation stage — a sequence of simple instructions like "load the constant 3," "load the constant 5," "add the top two values on the stack," "store the result into the variable named x." Each instruction is compact (historically literally one or two bytes per instruction, which is where the name comes from).
14 BINARY_OP 0 (+) 18 RETURN_VALUE
Let's decode this line by line:
Leftmost numbers (4, 5, 6, 7): The source line numbers this bytecode came from — this is exactly what lets CPython show you the correct line number in a traceback when an error occurs, even though execution is really happening at the bytecode level. RESUME : A modern housekeeping instruction (added in Python 3.11) marking the start of actual function execution, used internally for things like handling debuggers cleanly. LOAD_CONST 1 (3) : Look up index 1 in the code object's co_consts table (which holds the constant 3 ), and push that value onto the stack (an internal data structure the virtual machine uses to hold values temporarily — you'll see exactly how it works in 1.3). Think of the stack like a pile of plates: you can only add to or remove from the top. STORE_FAST 0 (x) : Pop the top value off the stack and store it into local variable slot 0 , which corresponds to the name x (from co_varnames ). "FAST" refers to the fact that local variables in a function are stored in a simple, pre-sized array indexed by number — much faster to access than looking a name up in a dictionary, which is how global variable access works ( STORE_NAME / LOAD_NAME , or LOAD_GLOBAL ), a distinction that matters a lot for performance (revisited in Module 4.1 and Module 7.1). The same pattern repeats for y = 5. LOAD_FAST 0 (x) and LOAD_FAST 1 (y) : Push the current values of x and y onto the stack, leaving two values sitting there. BINARY_OP 0 (+) : Pop the top two stack values, apply the + operation to them (this is the point where CPython's virtual machine ultimately triggers logic that, for plain integers, ends up doing work conceptually similar to the ALU addition traced in Module 0.1 — though wrapped in many layers of Python object handling we'll unpack in Module 3), and push the result back onto the stack. RETURN_VALUE : Pop the top stack value and return it as the function's result.
Notice how directly this maps onto the AST from 1.1: the Assign node became a LOAD_CONST + STORE_FAST pair; the BinOp with Add() became LOAD_FAST + LOAD_FAST + BINARY_OP. Bytecode compilation is essentially a mechanical, systematic flattening of the tree into an equivalent linear sequence.
Assuming bytecode is portable across CPython versions: It is not. Bytecode format, opcode numbers, and even opcode names change between Python versions (as you can see, the exact instructions above differ noticeably from older Python versions). Never try to reuse compiled .pyc files across different Python versions. Confusing bytecode with machine code: Bytecode is not something your CPU can execute directly — it's a custom format that only CPython's own virtual machine (1.3) understands. This is the core reason plain CPython is generally slower than compiled languages: there's an entire extra layer of software (the VM) interpreting these instructions, rather than the CPU executing native instructions directly. Not realizing local variable access ( LOAD_FAST ) is faster than global access ( LOAD_GLOBAL ): A very common, very real performance mistake beginners make (and even experienced developers overlook) is writing hot loops that repeatedly reference global variables or module-level names, not realizing each such access is a comparatively slower dictionary lookup, versus the simple indexed-array access used for locals. We'll exploit this fact directly in Module 7.1's optimization techniques.
Assuming every line of Python maps to one bytecode instruction: As you saw above, even a "simple" line like return x + y expands into four separate instructions. Complex expressions can expand into dozens.
1.3 The CPython Virtual Machine ( ceval.c )
Recall the stage director's cue sheet from 1.2 — a flat, numbered list of simple instructions. Now imagine a stagehand whose entire job is to stand there, read cue #1, execute it, read cue #2, execute it, and so on, one at a time, forever, until the show ends. That stagehand is the CPython Virtual Machine: a big loop, written in C, whose entire purpose is to repeatedly read the next bytecode instruction and carry out whatever it says — exactly mirroring the Fetch-Decode- Execute cycle from Module 0.1, except this "CPU" is itself just a program, running on top of a real CPU, interpreting Python-specific instructions instead of native machine instructions.
Stack-machine architecture: The design CPython's virtual machine uses to actually perform work: rather than instructions naming specific "registers" (like the real CPU registers from Module 0.1), most bytecode instructions operate on an implicit stack of values — pushing values on, popping them off, and pushing results back on, as we traced with LOAD_FAST / BINARY_OP in 1.2. This is simpler to generate correct bytecode for (compared to allocating real registers), at some cost in raw execution speed compared to a register-based design.
Evaluation loop ( PyEval_EvalFrameEx and the broader ceval.c ): The actual C function at the heart of CPython that implements the giant "read next instruction, act on it" loop. Historically centered in a CPython source file called ceval.c ("c evaluate"), this is genuinely one giant loop that runs for the entire lifetime of every piece of Python code you ever execute — from the moment your script starts to the moment it ends. PyEval_EvalFrameEx specifically refers to the (C-level) function responsible for evaluating one stack frame's worth of bytecode (see below for what a "frame" is).
Stack frame ( PyFrameObject ): An object CPython creates every time a function is called, representing that specific call's private execution context: its own local variables, its own value stack (for intermediate computation results), and a reference to the code object (1.2) being executed, plus a pointer back to whichever frame called it (so execution can resume there once this function returns). When you see a Python traceback with multiple "File ... line ... in function_name" entries, you are literally looking at a printed chain of these stack frames, from the outermost call down to wherever the error occurred.
Local / fast locals namespace: The array-like storage (accessed via LOAD_FAST / STORE_FAST , as seen in 1.2) where a function's local variables live during its execution, held inside that call's PyFrameObject. Because local variables are known and fixed at compile time (CPython determines exactly which names are local to a function while generating its
Store it into fast-locals slot 0 (the slot reserved for 'x'). Value stack now: [] Fast locals: [x=3, y=]
INSTRUCTION: LOAD_CONST 2 (5) PUSH 5 onto the value stack. Value stack now: [5]
INSTRUCTION: STORE_FAST 1 (y) POP 5, store into fast-locals slot 1 ('y'). Value stack now: [] Fast locals: [x=3, y=5]
INSTRUCTION: LOAD_FAST 0 (x) Read fast-locals slot 0 (value 3) WITHOUT removing it from there. PUSH a reference to that value onto the value stack. Value stack now: [3]
INSTRUCTION: LOAD_FAST 1 (y) PUSH a reference to fast-locals slot 1's value (5). Value stack now: [3, 5]
INSTRUCTION: BINARY_OP 0 (+) POP two values off the stack: 5 (top), then 3. Dispatch to the addition implementation for these operand types (both are Python int objects -> this eventually calls into the integer type's addition logic, previewed fully in Module 3.2). The result, a NEW integer object with value 8, is computed. PUSH 8 onto the value stack. Value stack now: [8]
INSTRUCTION: RETURN_VALUE POP the top of the value stack (8) -> this becomes the return value. The current PyFrameObject is discarded (its locals x=3, y=5 no longer exist anywhere once the frame is gone -- this is why local variables don't persist between calls). Control returns to the CALLER's frame (the module-level code that wrote result = add_numbers()), which now stores 8 into its own 'result' variable.
Every single one of these steps is the evaluation loop reading one bytecode instruction, dispatching to the correct opcode-handling logic, mutating either the value stack or the fast-locals array, and advancing the instruction pointer — round and round, exactly mirroring the Fetch-Decode-Execute cycle of a real CPU (Module 0.1), except entirely implemented in software, one Python-specific "instruction" at a time.
Believing Python "runs the AST directly": A common misconception is that Python somehow walks the tree from 1.1 at runtime. It does not — by the time your code actually executes, the tree has already been fully flattened into bytecode (1.2), and it's that linear bytecode the virtual machine executes, via the stack-based mechanism traced above. The AST only exists transiently during compilation. Assuming local variables "leak" between function calls: Because each call creates a brand-new PyFrameObject with a brand-new fast-locals array, there is no memory connection between one call's x and the next call's x (unless you're dealing with mutable default arguments or closures — special cases covered in Module 4.1 and 4.3).
Beginners sometimes expect state to persist across calls "because the variable name is the same"; it doesn't, by default. Underestimating the overhead of the interpretation loop itself: Every single bytecode instruction — even something as simple as loading a constant — involves the evaluation loop reading the opcode, dispatching to handler logic, and manipulating the stack. This per-instruction overhead is the fundamental reason why equivalent code in a compiled language (running as raw native CPU instructions, no interpreting layer) is typically much faster than CPython — a gap this entire syllabus eventually addresses directly via Cython and native interop in Module 7.3. Confusing the "value stack" (per-frame, used for expression evaluation) with the "call stack" (the chain of frames from caller to callee): These are two different, related concepts. Each frame has its own internal value stack for evaluating expressions (as traced above); separately, frames themselves are chained together (each pointing back to its caller) forming the call stack you see represented in tracebacks.
Using pen and paper (no computer), manually trace the value stack and fast-locals array, instruction by instruction, for the following bytecode-equivalent function, the same way this section traced add_numbers() :
def compute(): a = 10 b = 4 c = a - b return c * 2
For each step, write down: (1) which opcode would run, (2) the value stack's contents immediately after that instruction, and (3) the fast-locals array's contents immediately after that instruction. Confirm your final answer is a returned value of 12.
Term One-Line Definition
Lexical analysis / tokenizing Breaking source text into meaningful tokens
Token Smallest meaningful unit of source code (keyword, name, literal, operator)
Grammar (CFG) Formal rules defining what token sequences are valid Python
Parser Converts a token stream into a structured tree per grammar rules
PEG parser The parsing algorithm CPython uses since 3.
AST Tree structure representing a program's structural meaning
ast module Standard-library tool to parse/inspect/modify ASTs from Python
Control Flow Graph Representation of all possible execution paths through code
Bytecode compilation Flattening the AST into a linear sequence of simple instructions