1

the below is what confuses me:

In terminal, I tried these codes:

>>> a = 1900
>>> b = 1900
>>> a is b
False
>>> c = 1
>>> d = 1
>>> c is d
True

As I think, these result comes from what I read from this post: what is difference between [None] and [] in python?: Python caches small integer objects for performance reasons. So 'a is b' will return false because they point to different objects (obviously they are not small integer objects).

But when I try this part of code on PyCharm venv, the result comes to different:

a = 1900
b = 1900
print(a is b)
console shows 'True'

Why does this happen? they have the same python version:

Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 03:13:28) 
[Clang 6.0 (clang-600.0.57)] on darwin
ccc
  • 11
  • 2
  • Because the interpreter is free to cache immutable built-in types like `int`. This is an implementation detail, not something that can be relied on. Typically, literals are cached in a code block at compile time. When you write it in a REPL, each line is compiled/executed as a separate block, however, when you execute the code as a script, it's just one block. – juanpa.arrivillaga Apr 22 '20 at 08:18
  • 1
    I added a more appropriate duplicate target that explains it in detail. – juanpa.arrivillaga Apr 22 '20 at 08:20
  • I don't think this question is a duplicate. https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is is not a duplicate because here the OP _already knows_ that "Python caches small integer objects for performance reasons", and they also never mention the equality operator in the question. https://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers is not a duplicate either because it doesn't explain why the `is` operator behaves _differently_ in the terminal and in the IDE. [Check this answer](https://stackoverflow.com/a/49472348/4354477) – ForceBru Apr 22 '20 at 08:20
  • 1
    Okay, now _this_ is a way better duplicate target! – ForceBru Apr 22 '20 at 08:22
  • Note, again, CPython will create a small integer cache at interpreter start-up. However, the runtime is free to cache *other ints* during runtime or when your code is compiled as it sees fit. Note also, small integers will sometimes produce new objects, there are some edge cases (basically built-in functions that return integers that don't utilize the cache). All of these are *implementation details that shouldn't be relied upon*. What is surprising is that they should ever be the same object at all. – juanpa.arrivillaga Apr 22 '20 at 08:23
  • 1
    @juanpa.arrivillaga thx for your explanation! – ccc Apr 22 '20 at 08:36

0 Answers0