Why does "a is b" behave differently in interactive mode and when does it work from a script?

When I tried to answer the question about using the is keyword, I realized that this code:

Script:

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

Interactive mode:

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

provided different results interactively in Python and when it was run from a script.

From this answer :

The current implementation saves 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.

So, I would expect a is b return True only for integers in the range [-5, 256] . But this is true only in interactive mode, and not when it is executed from a script.

Question: Why does a is b behave differently in interactive mode and when does it work from a script?


Note: Tested in Python 2.7 and Python 3

+6
source share
1 answer

The difference is how constants are handled. In interactive mode, it is impossible to say if a constant number already exists or not. But for compiled code, each constant is internally stored in the table, and duplicates are deleted. But this is implementation detail and does not have to be true for each version of python.

+1
source

Source: https://habr.com/ru/post/970534/


All Articles