Python string interning -


While there is no real use in the behavior of this question, I'm curious how the Python string interns. I have noticed the following.

  & gt; & Gt; "String" is "string" & gt; & Gt; This is true   

It was just like I expected.

You can also do this.

  & gt; & Gt; "String" + "G" is "string" & gt; & Gt;  

S1 = "strin" & gt; & Gt; S2 = "string" & gt; & Gt; S1 + "g" is s2 & gt; & Gt; Incorrect

Python does not have an evaluation of s1 + "g" , it is realized that it is like s1 and it is the same Point to the address? In fact, what is happening in that last section from which it is incorrect

Implementation is specific, but your interpreter is probably stabilizing the compilation time, but not the result of run-time expressions.

I use CPython 2.7.3 of the following.

In the second example, the expression "strin" + "g" is compiled at the time of compilation, and replaced with "string" is. Earlier two examples behave the same.

If we examine the bytecodes, we will see that they are exactly the same: # s1 = "string" 2 0 LOAD_CONST 1 ('string') 3 STORE_FAST 0 (s1) # s2 = "strin" + "g" 3 6 LOAD_CONST 4 ('string') 9 STORE_FAST 1 (s2)

Third example includes a run-time consensus As a result, it is not automatically interned:

  # s3a = "strin" # s3 = s3a + "g" 4 12 LOAD_CONST 2 ('strin') 15 STORE_FAST 2 ( S3a) 5 18 LOAD_FAST 2 (s3a) 21 LOAD_CONST 3 ('G') 24 Binari_Add 25 STORE_FAST 3 (S3) 28 LOAD_CONST 0 (none) 31 Return_Wall   
 > gt; ; & Gt; & Gt; S3a = "strin"> gt; & Gt; & Gt; S3 = s3a + "g"> gt; & Gt; & Gt; S3 "string" false and gt; & Gt; & Gt; Intern (S3) is "string" true    

Comments

Popular posts from this blog

excel vba - How to delete Solver(SOLVER.XLAM) code -

github - Teamcity & Git - PR merge builds - anyway to get HEAD commit hash? -

ios - Replace text in UITextView run slowly -