0

I just learnt about Python singletons today. But when I am trying my code in VS Code, it acts weird. Here's the code I'm trying:

num_1 = 1007
num_2 = 1007

var1 = [i for i in range(250, 260)]
var2 = [i for i in range(250, 260)]

for i, j in zip(var1, var2):
    print(i, i is j)

print(num_1 is num_2)

Here's VS Code's terminal output:

250 True
251 True
252 True
253 True
254 True
255 True
256 True
257 False
258 False
259 False
True

num_1 is num_2 is returning True when it should return False. I have tried in my PC's terminal and that is giving the correct output. I don't understand why it's acting differently in VS Code

Mbugua_J
  • 47
  • 8
  • Interesting explanation in linked duplicate. tl;dr you want to use `==`, not `is`. – Samwise Oct 04 '21 at 04:57
  • @Samwise I don't think my question is the same as the alleged duplicate. also the '==' tests equality while the 'is' is testing if they refer to the same object. When it comes to singletons, it should only return true up to 256, like it's doing in the for loop. And it behaves as it should in the PC terminal...my question is more about why VS Code is acting differently. I have never had a situation before where the two terminals are acting differently – Mbugua_J Oct 04 '21 at 05:05
  • This is addressed in one of the answers in the dupe; the behavior is different by Python version/implementation, and I expect if you dig a little deeper you'll find that VSCode is using a different Python executable from the terminal. – Samwise Oct 04 '21 at 13:59
  • Also worth noting that this deduping behavior is an implementation detail of the interpreter, not a feature of the language you should code around, and definitely not the same thing as using a singleton pattern in your own code! You can read about that here: https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python – Samwise Oct 04 '21 at 16:09

0 Answers0