Yesterday I came across this odd unpacking difference between Python 2 and Python 3, and did not seem to find any explanation after a quick Google search.
Python 2.7.8
a = 257
b = 257
a is b # False
a, b = 257, 257
a is b # False
Python 3.4.2
a = 257
b = 257
a is b # False
a, b = 257, 257
a is b # True
I know it probably does not affect the correctness of a program, but it does bug me a little. Could anyone give some insights about this difference in unpacking?
This behaviour is at least in part to do with how the interpreter does constant folding and how the REPL executes code.
First, remember that CPython first compiles code (to AST and then bytecode). It then evaluates the bytecode. During compilation, the script looks for objects that are immutable and caches them. It also deduplicates them. So if it sees
it will store a and b against the same object:
Note the
LOAD_CONST 1
. The1
is the index intoco_consts
:So these both load the same
257
. Why doesn't this occur with:?
Each line in this case is a separate compilation unit and the deduplication cannot happen across them. It works similarly to
As such, these code objects will both have unique constant caches. This implies that if we remove the line break, the
is
will returnTrue
:Indeed this is the case for both Python versions. In fact, this is exactly why
returns
True
as well; it's not because of any attribute of unpacking; they just get placed in the same compilation unit.This returns
False
for versions which don't fold properly; filmor links to Ideone which shows this failing on 2.7.3 and 3.2.3. On these versions, the tuples created do not share their items with the other constants:Again, though, this is not about a change in how the objects are unpacked; it is only a change in how the objects are stored in
co_consts
.