4

I am using Visual Studio Code's Jupyter Notebook on Windows, with Python version 3.9.13 and CPython implementation. The result of two code blocks below are different.

a = 257
b = 257
print(a is b)       # False
if True:
    a = 257
    b = 257
    print(a is b)       #True

I understood that the integer 257 is not interned, which means that I expected the output to be False. However, when I added one indentation, the output became True. I tested this using both for and while loops instead of an if statement, and the result was the same. Additionally, I tested this on the terminal, and the result was also the same. However, when I tested this in a .py file, both results were True.

Thank you.

Brian61354270
  • 8,690
  • 4
  • 21
  • 43
윤석진
  • 41
  • 3
  • 4
    Do note that anything that's given in an answer here will be an observation on the implementation, rather than on the language specification (which deliberately leaves all this undefined). Thus, if you write code that assumes any particular behavior, you're relying on undefined behavior that can break without notice in future releases -- so it's best to not make assumptions either way, as opposed to building your mental model based on empirical observations that can become wrong at any time. – Charles Duffy Feb 28 '23 at 18:21
  • "Assume nothing, question everything". basically paraphrasing from what I understood above – rv.kvetch Feb 28 '23 at 18:23
  • Can reproduce this in a jupiter notebook in vscode with python 3.9 and 3.11 – tetris programming Feb 28 '23 at 18:23
  • 8
    This isn't the result of interning, but of de-duping constants at compile time. The compiler can only de-dupe constants that are part of the same round of interpretation. So, in a file or in the same REPL statement = duplicated constants can be optimized into a single object, but in different REPL statements = different objects. – Brian61354270 Feb 28 '23 at 18:27

0 Answers0