Python Bytecode: Disassembling Code with dis
CPython compiles source code into intermediate bytecode instructions. The `dis` module disassembles callables so you can inspect exact virtual machine operations ⚙️.
import dis
def add(a, b):
return a + b
dis.dis(add)
# Outputs bytecode instructions:
# LOAD_FAST, BINARY_OP, RETURN_VALUE ⚙️
# 69. Python Bytecode: Disassembling Code with dis CPython compiles source code into intermediate bytecode instructions. The `dis` module disassembles callables so you can inspect exact virtual machine operations ⚙️. ```python import dis def add(a, b): return a + b dis.dis(add) # Outputs bytecode instructions: # LOAD_FAST, BINARY_OP, RETURN_VALUE ⚙️ ``` Disassembling code proves why certain constructs are faster than others (e.g. list comprehension vs `.append()`). You see the exact virtual machine instructions! ⚙️ --- ### Question What does the `dis.dis()` function do in Python? 🧠 - [ ] a. Disassembles Python functions or code blocks into readable CPython bytecode ⚙️ - [ ] b. Disables all garbage collection for the function - [ ] c. Compiles Python directly into x86 machine assembly code - [ ] d. Deletes the bytecode cache files (.pyc) --- ### Challenge Import `dis`. Disassemble `lambda x: x * 2` using `dis.dis(...)`. 🎯 <details> <summary>Solution</summary> ```python import dis dis.dis(lambda x: x * 2) ``` </details>