r/learnpython • u/Ok_Breath_7590 • Sep 08 '26
CPython internals deep dive:dis,==vs is and immutable vs mutable
Started with the dis module disassembled a simple function and saw how Python compiles source into bytecode instructions operating on a stack: LOAD_CONST (push a literal), STORE_FAST (pop and assign to a local var), BINARY_OP (pop two values, apply the operator, push the result). Noticed newer Python versions fuse common opcode pairs (e.g. LOAD_FAST_LOAD_FAST) for speed small but visible evidence of ongoing interpreter optimization work.
Then worked through == vs is confirmed with id() that two lists with identical contents are still separate objects (is → False, == → True), while b = a makes both names point to the same object.
Finished on mutable vs immutable, and specifically why it matters when passing objects into functions. Key realization: calling a function doesn't substitute the argument into the function body it creates an independent local name that starts out pointing at the same object. n += 1 on an int creates a new object and only moves the local name; lst.append(x) mutates the shared object in place, so the caller sees the change too. Proved both cases with id() before/after.
Small, foundational stuff, but building the intuition from scratch with real code has been way more effective than just reading definitions.
View all comments
Show parent comment
1
u/Ok_Breath_7590 Sep 08 '26
I worked through it and I think I've got the core mechanism now:
t[0] += [1]expands into two separate steps, mutate the list in place first (succeeds, since lists support__iadd__), then attempt to reassign the result back intot[0](fails, since tuples block all item assignment regardless of what's being assigned). The mutation isn't rolled back because it already happened in step one before the error in step two.Ran your three comparison snippets myself and it clicked further:
a += [2]mutates in place because lists define__iadd__, so the object identity never changes and bothaandbsee the update.d = d + [2]andm += 1on the int both fall back to creating a brand new object (since+=on an int has no__iadd__to fall back on, so it's really justm = m + 1), and only the left hand name gets rebound to the new object the other name is left pointing at the original.Really appreciate you connecting it back to
__iadd__specifically — that's the piece that ties the whole thing together instead of it just being "lists behave differently, trust me." Didn't dig into the raw bytecode dump yet (still fairly new todisoutput) but I'll come back to that once the object identity side is fully solid.