0

I know Python has a cache for objects with numerical values between -5 and 256. I can confirm this in Python interactive window (console). For example,

a = -10
b = -10
print(id(a))
1797396904912
print(id(b))
1797396904976
print(id(a) == id(b))
False

However, when I run exactly the same code via a script:

a = -10
b = -10
print(id(a))
print(id(b))
print(id(a) == id(b))

I get:

1797396904848
1797396904848
True

What's going on? (The question has nothing to do with another question on id of strings with and without a space).

martineau
  • 119,623
  • 25
  • 170
  • 301
Oleg
  • 311
  • 2
  • 3
  • 7
  • Not a duplicate. Completely different problem. – Oleg Oct 02 '19 at 20:51
  • Why do you expect them to be the same? – martineau Oct 02 '19 at 21:30
  • Exactly the same code works differently in the interactive window and when it is run as a script. In one case, the objects are different. In the other, the id’s are the same. – Oleg Oct 02 '19 at 23:38
  • 1
    The issue here, btw, is that Python will cache immutable literals in the same code block. When you execute as a module, they are in the same block. In a repl, these will be different blocks. This is all implementation details and could change unannounced at any moment – juanpa.arrivillaga Dec 21 '21 at 05:16

1 Answers1

0

No one seems to have an answer. I did a bit more exploration and found out that the problem exists in Anaconda but not in IDLE for a = -10 and b = -10.

However, the problem exists for c = 257 and d = 257. Different id(c) and id(d) when running in the interactive window. Same id(c) and id(d) when running IDLE script.

Oleg
  • 311
  • 2
  • 3
  • 7