Running:
a = 257
b = 257
print id(a) == id(b)
Results in:
Same statement but opposite results. Why?
test.py
is parsed together which is more optimizable than the code parsed as separate statements in the interpreterWhen you put it in a test.py
and run it as a whole, the byte code compiler has a better chance of analyzing the usage of literals and optimizing them. (Hence you get a
and b
pointing to the same place)
As opposed to when you run the separate statements (parsed separately) in the interpreter (where I think it only optimizes up to 256 but not 257 via preallocation)
Play with this in the interpreter to see the effect of separate statements:
>>> a, b = 257, 257 # or if you prefer: a = 257; b = 257
>>> print a is b
True
>>> a = 257
>>> b = 257
>>> print a is b
False
Defining a function in the interperter also gives it a change to analyze and optimize the used literals
>>> def test():
... a = 257
... b = 257
... print a is b
...
>>> test()
True
[-5, 256]
range are)>>> def test():
... pi = 3.14
... x = 3.14
... return x is pi
...
>>> test()
True
# As opposed to separate statements:
>>> pi = 3.14
>>> x = 3.14
>>> x is pi
False
>>> dis.dis(test)
2 0 LOAD_CONST 1 (3.14)
3 STORE_FAST 0 (pi)
3 6 LOAD_CONST 1 (3.14) <-- Same constant 1 reused
9 STORE_FAST 1 (x)
4 12 LOAD_FAST 1 (x)
15 LOAD_FAST 0 (pi)
18 COMPARE_OP 8 (is)
21 RETURN_VALUE