When a Python interpreter deals with a .py file, is it different from working with a single expression?

Duration:

a = 257 b = 257 print id(a) == id(b) 

Results in:

same operator enter image description here

The same statement, but opposite results. What for?

+6
source share
1 answer

The code in test.py parsed together, which is more optimized than the code parsed as separate instructions in the interpreter

When you put it in test.py and run it as a whole, the byte code compiler is more likely to analyze the use of literals and optimize them. (Therefore, you get a and b pointing to the same place)

Unlike when you run separate interpreters (separately understood) in the interpreter (where I think it optimizes only to 256, not 257 through preallocation)

Play with this in the interpreter to see the effect of individual 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 an interoperator also makes it possible to analyze and optimize the literals used.

 >>> def test(): ... a = 257 ... b = 257 ... print a is b ... >>> test() True 

This optimization is not limited to integers, it works, for example. for float too (floats do not fall under caching as integers in the range [-5, 256] )

 >>> 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 

Looking at the byte code to see that it really uses the same constant

 >>> 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 
+10
source

All Articles