3
a = 1234
b = 1234
print(id(a), id(b))

In the above script both IDs are the same. a and b refer to the same object. When running the commands one by one in a Python console the IDs are different:

>>> a = 1234
>>> b = 1234
>>> print(id(a), id(b))
2445680 6579168

but:

>>> print(id(1234), id(1234))
6579472 6579472

Why is 1234 a different object in successive commands, but not in one command or in a script?

I tested this on CPython 3.5.2.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
MB-F
  • 22,770
  • 4
  • 61
  • 116
  • I don't think this is about caching. If you do `print(id(1234), id(1234))` Python can throw away the first value after printing it and will reuse the space for the second value. – Matthias Feb 08 '17 at 08:50
  • 1
    It's not straightforward dupe, but essentally it's about how and when `co_consts` are built. In REPL it's per line, in script mode it's once per script file. – Łukasz Rogalski Feb 08 '17 at 08:52
  • 2
    Bottom line, don't use identity for integers, you're in the murky waters of CPython implementation details, two related questions http://stackoverflow.com/questions/34147515/is-operator-behaves-unexpectedly-with-non-cached-integers and http://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers – Chris_Rands Feb 08 '17 at 09:03
  • @ŁukaszRogalski I expected something like this but did not know what to look for. The answer you linked to is rather verbose but makes sense after reading 2-3 times and eliminating the string-specific noise :) – MB-F Feb 08 '17 at 09:03
  • 1
    Actually, the first question linked by @Chris_Rands is the more accurate duplicate. – MB-F Feb 08 '17 at 09:07
  • Agreed, now I understand it too :) @Jean-FrançoisFabre I think multiple dupe targets can be given? Are you able to add the **first** link by Chris_Rands as it's much more applicable than the one that's been approved by Community. – roganjosh Feb 08 '17 at 09:09
  • 1
    Since it's closed, I'm not going to reopen again to close it. I think it's possible when non python gold badge owners close with a different duplicate, but not with a single-handed close. Let's leave it that way with Chris good comments and links. I think everyone gets it now :) – Jean-François Fabre Feb 08 '17 at 09:13
  • I added the dupe to the dupe list and edited your question to remove the note, hope you don't mind :-). – Dimitris Fasarakis Hilliard Jun 03 '17 at 19:31

0 Answers0