Inspecting CPython Bytecode with `dis.get_instructions`
CPython is a stack-based virtual machine. Code compiles into compact bytecode instructions. `dis.get_instructions(func)` yields structured `Instruction` objects exposing opcodes, arguments, and byte offsets ⚙️.
import dis
def compute(a, b):
return a + b
for inst in dis.get_instructions(compute):
print(f"{inst.opname:<16} arg={inst.argval!r} ⚙️")
# 69. Inspecting CPython Bytecode with `dis.get_instructions` CPython is a stack-based virtual machine. Code compiles into compact bytecode instructions. `dis.get_instructions(func)` yields structured `Instruction` objects exposing opcodes, arguments, and byte offsets ⚙️. ```python import dis def compute(a, b): return a + b for inst in dis.get_instructions(compute): print(f"{inst.opname:<16} arg={inst.argval!r} ⚙️") ``` In modern CPython (3.11+ and 3.13), the specializing adaptive interpreter dynamically fuses instructions (like `LOAD_FAST_LOAD_FAST`) to accelerate execution without a traditional JIT 🏎️! --- ### Question What virtual machine architecture does CPython use to execute compiled bytecode instructions? 🧠 - [ ] a. A stack-based virtual machine where instructions push and pop items on a per-frame value stack ⚙️ - [ ] b. A pure register-based architecture with 32 fixed internal virtual registers - [ ] c. A discrete finite automaton utilizing tape-head memory cells - [ ] d. A direct hardware execution pipeline bypassing memory frames --- ### Challenge Define `def square(x): return x * x`. Inspect its instructions using `dis.get_instructions`. Check if `'RETURN_VALUE'` is in the list of opnames and print the boolean. 🎯 <details> <summary>Solution</summary> ```python import dis def square(x): return x * x opnames = [inst.opname for inst in dis.get_instructions(square)] print('RETURN_VALUE' in opnames) ``` </details>