Python executable compiled from source code at https://github.com/python/cpython/commit/efd223da0c4be9384e07f9d43328bf9528d02145
see Working w- Source Code on how to build

Starting with just few lines of code in test.py which does a simple addition before printing result

a = 8
b = 4
c = a + b
print(c)

Now, the python disassembler can show us what operations are happening wrt every line of code, and dis can be found at https://github.com/python/cpython/blob/main/Lib/dis.py

Disassembling code

running dis on code is simple as well

image 30.png

the first column is line number wrt script, next is the instruction then the value given to that op

Understanding disassembly w/ Bytecode Instructions

Value Stack

the value stack is what the intructions/ops work on like they pop the top to get some values and similarly push values into the stack

Line 0

RESUME is a no-op which doesn’t do anything

Line 1 & 2

instead of LOAD_CONST , LOAD_SMALL_INT is used, which is an optimization for small integers under 256

STORE_NAME pops value from stack based on arg

Line 3

BINARY_OP will pop top of value stack twice and add result to stack again

rhs = STACK.pop()
lhs = STACK.pop()
STACK.append(lhs op rhs)

for addition, the value is 0

Line 4

here, LOAD_NAME went all the way up to built-ins for print through local, global vars


https://docs.python.org/3/library/dis.html gives some idea on what exactly happening within the instruction

bunch of opcodes related to these instructions can be seen here (though they’re trivial to remember)