Question

From this link I learnt that

The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object

But when I tried to give some example for my session and I found out that it behaves differently with assignment and tuple unpacking.

Here is the snippet:

>>> a,b = 300,300
>>> a is b
True
>>> c = 300
>>> d = 300
>>> c is d
False
Was it helpful?

Solution

Because int is immutable, Python may or may not use exists object, if you save the following code in to 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 compile the code, it may reuse all the constants. Becasue you input your code in a python session, the codes are compiled line by line, Python can't reuse all the constants as one object.

The document only says that there will be only one instance for -5 to 256, but doesn't define the behavior of others. For immutable types, is and is not is not important, because you can't modify them.

OTHER TIPS

 import dis

 def testMethod1():
     a, b = 300, 300

 print dis.dis(testMethod1)

Prints:

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 (None)
15 RETURN_VALUE None

 def testMethod2():
     a = 300
     b = 300

Prints:

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 (None)
15 RETURN_VALUE None

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 discovered that both methods return False eventually; however, on one run only, ie not putting the methods in a loop, they seem to always return True. Sometimes it uses a single reference, and sometimes it does not.

The documentation only states that -5 to 256 will return the same reference; hence, you simply just shouldn't be using is for comparison (in this case) as the number's current id has no guarantee on it.

NB: You never want to use is for comparison of values, as that's not what it's for, it's to compare identities. My point was that is's return value is not always going to be True when you're outside of the defined range.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top