6

While trying to answer a question about the use of the is keyword, I figured out that this code:

Script:

a = 123456
b = 123456
print a is b # True

Interactive mode:

>>> a = 123456
>>> b = 123456
>>> a is b
False

was giving different outputs on Python Interactive mode and when it was ran from a script.

From this answer:

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.

So, I would expect that a is b returned True only for integers in the range [-5, 256]. But it is only true on Interactive mode, not when it is ran from a script.

Question: Why does a is b behaves differently on Interactive mode and when it's ran from script?


Note: Tested in Python 2.7 and Python 3

Community
  • 1
  • 1
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73

1 Answers1

1

The difference is, how constants are handled. In interactive mode, there is no way to say, if a number constant is already there or not. But for compiled code, every constant is internally saved to a table, and duplicates are removed. But this is a implementation detail, and need not be true for every python version.

chepner
  • 497,756
  • 71
  • 530
  • 681
Daniel
  • 42,087
  • 4
  • 55
  • 81