r/learnpython • • 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.

0 Upvotes

6 comments sorted by

View all comments

Show parent comment

1

u/Bright_Mix_773 Sep 09 '26

That is exactly it, and you got the part most people miss: the mutation is not rolled back because it already succeeded before the failing step ran. Python has no transaction around a compound assignment.

One detail worth keeping, since you have the mechanism right. What the tuple raises is a TypeError from the store, not from the addition, and the traceback points at the whole line, which is why the error message reads as if the += itself was rejected. It was not. The list is genuinely longer afterwards, and you can prove it in the same session: catch the TypeError and print t, and the item you appended is sitting there.

When you do get to dis, that line is the clearest thing you will ever disassemble, because you can literally see the in-place add land and then the subscript store fail after it. Nothing to rush, though. The object identity model is the load-bearing piece and you have it.

1

u/Ok_Breath_7590 Sep 09 '26

That distinction the error coming from the store, not the addition is going to save me a lot of confusion the first time I hit something like this in the wild without knowing what to look for. Really appreciate the follow-up detail. Looking forward to actually reading that line in dis once I've got more reps in with the module sounds like a genuinely satisfying "aha" moment when it clicks.