How is unpacking a tuple different from a regular destination?

From this link, I learned that

The current implementation stores an array of integer objects for all integers from -5 to 256, when you create an int in this range, you actually just return a reference to an existing object

But when I tried to give an example for my session, I found out that it behaves differently while unpacking and distributing packets.

Here is a snippet

Python 2.7.2 (default, Oct 11 2012, 20:14:37) [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> a,b = 300,300 >>> a is b True >>> c = 300 >>> d = 300 >>> c is d False >>> 
+8
python cpython
source share
2 answers

Since int is immutable, Python may or may not use an existing object, if you save the following code in a script file and run it, it will output two True.

 a, b = 300, 300 print a is b c = 300 d = 300 print c is d 

When Python compiles the code, it can reuse all constants. Try to enter your code in a python session, the codes are compiled line by line, Python cannot reuse all constants as a single object.

The document only says that there will be only one instance for -5 to 256, but does not determine the behavior of others. For immutable types, is and is not not important because you cannot change them.

+7
source share
  import dis def testMethod1(): a, b = 300, 300 print dis.dis(testMethod1) 

Print

4 0 LOAD_CONST 2 ((300, 300))
3 UNPACK_SEQUENCE 2
6 STORE_FAST 0 (a)
9 STORE_FAST 1 (b)
12 LOAD_CONST 0 (no)
15 RETURN_VALUE No

  def testMethod2(): a = 300 b = 300 

Print

7 0 LOAD_CONST 1 (300)
3 STORE_FAST 0 (a)
8 6 LOAD_CONST 1 (300)
9 STORE_FAST 1 (b)
12 LOAD_CONST 0 (no)
15 RETURN_VALUE No

So, it looks essentially the same, but with LOAD_CONST in one step in the first method and two steps in the second method ....

EDIT
After some testing, I found that both methods return False in the end; however, with one run, i.e. without putting the methods in a loop, they seem to always return True . Sometimes it uses one link, and sometimes not.

The documentation only states that from -5 to 256 will return the same link; therefore, you simply should not use is for comparison (in this case), since the current id number has no guarantee.

NB: you never want to use is to compare values, as that is not what it is necessary for to compare identifiers. My point was that the return value of is will not always be True when you are outside the given range.

+2
source share

All Articles