-1

As far as I know, in Python, [-5, 256] integers are small integers. So, I hope my result as below

a=300
b=300
a is b //False

but on my computer, it's pretty different someone can explain this please...

enter image description here

I tried to find the problem in the python document, but nothing much...

p.s. My environment is:

' Python 3.10.2 (v3.10.2:a58ebcc701, Jan 13 2022, 14:50:16)

[Clang 13.0.0 (clang-1300.0.29.30)] on darwin' in Mac

Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
  • are you compiling your file as `.py` and checking it? – Talha Tayyab Apr 24 '23 at 06:23
  • https://stackoverflow.com/questions/2195964/pythons-layout-of-low-value-ints-in-memory – Kostas Nitaf Apr 24 '23 at 06:39
  • "As far as I know, in Python, [-5, 256] integers are small integers." this is an implementation detail of the CPython VM, what are you trying to test that for? Also the CPython VM has basic optimisations, here it's deduplicating the two identical constants into the same `co_const` slot, so your `a` and `b` literally are the same object at the code level, before even involving the small integer cache. – Masklinn Apr 24 '23 at 06:40
  • 1
    Caching is an implementation detail and you shouldn't rely on `is` to compare *values*. Use it to see if two names refer to the *same object*. Use `==` to compare *values*. – Mark Tolonen Apr 24 '23 at 06:41

1 Answers1

1

This is happening because the whole block is compiled before being run. Compiler is trying to optimize. Even if you run this code in idle or rep:

def check():
    a = 1000
    b = 1000
    print(a is b)

check()

#output
True

If you type in the Python shell each line is a completely different statement, parsed and compiled separately, thus:

>>> a = 257
>>> b = 257
>>> a is b

#output
False
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44