Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "a is b" behave differently on Interactive mode and when it's ran from script? [duplicate]

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

like image 846
Christian Tapia Avatar asked Jun 08 '14 12:06

Christian Tapia


People also ask

What is the purpose of the interactive mode?

Interactive mode is a command line shell which gives immediate feedback for each statement, while running previously fed statements in active memory. As new lines are fed into the interpreter, the fed program is evaluated both in part and in whole.

What are interactive mode in Python?

Interactive Mode Script Mode. It is a way of executing a Python program in which statements are written in command prompt and result is obtained on the same. In the script mode, the Python program is written in a file. Python interpreter reads the file and then executes it and provides the desired result.

What is integer caching in Python?

What is small integer caching? Python caches small integers, which are integers between -5 and 256 . 00:00 I'll put it for you under the title of small integer caching. 00:09 If I say a = 30 and b = 30 , so same thing as before, but we're using 30 instead of 300 .


1 Answers

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.

like image 170
Daniel Avatar answered Nov 01 '22 10:11

Daniel