Exploring CPython's bytecode
summary
Walks the .pyc layout (magic number, timestamp, code object) and uses the standard library marshal and imp to read Python 3.2 bytecode, dis to inspect opcodes, then implements a tiny Python VM in Python that creates frame objects, an instruction pointer and a stack and executes LOAD_FAST/STORE_FAST, MAKE_FUNCTION, CALL_FUNCTION and arithmetic ops successfully. It skips defaults, keyword and keyword-only args, is intentionally slow but functional, and notes a hidden limit: bytecode argument encoding caps positional args at 255 arguments. VM loop and frame object implemented in pure Python.
AI-written summary · about
chapters (38)
- 0:00Intro
- 1:26Unravelling Bytecode
- 2:32Python: Compiler & VM
- 3:45Python overview
- 4:21Example Module
- 5:07Executing the Bytecode
- 7:33Optimisation
- 8:55Structure of .pyc Files
- 10:07Magic Number
- 11:53Timestamp
- 12:16Code Object Marshal module
- 14:08Back to the Compiler Compile your own code object
- 16:28Code Objects It's documented: Data model (Language Reference) Everything which is executed becomes a code
- 19:21sum Code Object
- 20:59Disassembler
- 24:10First Taste of Bytecode (2) LOAD FAST
- 24:36First Model of the VM
- 26:04Reading Bytecode
- 27:07Bytecode Arguments dis HAVE ARGUMENT = 90
- 27:38First Eval Loop
- 29:25Passing Arguments
- 31:15Handling Bytecodes
- 31:32LOAD FAST LOAD CONST
- 31:57BINARY MULTIPLY
- 33:37BINARY ADD
- 34:01RETURN VALUE
- 34:24The VM So Far
- 34:48Disassembling the Module
- 38:22STORE NAME LOAD NAME
- 43:35CALL FUNCTION (2)
- 44:05POP JUMP_IF_FALSE
- 44:31JUMP FORWARD . POP TOP
- 45:14Incomplete
- 45:29EXTENDED ARG
- 46:00Abusing Bytecode
- 46:10The Tools
- 46:20Improve Tracing
- 46:58Questions
related talks
32mBytecode and .pyc files
30mA Bit about Bytes: Understanding Python Bytecode
01h 21mExploring Python Code Objects
34mCPython internals and the VM
22mLow Level Python a Deep dive into the python sources
31mUnderstanding Python from the inside: C concepts to dive into CPython fearless
01h 03mA tour of CPython's runtime
41mHow to write a JIT compiler in 30 minutes
