-2

I am a little bit confused about the immutability of integers in Python and the behavior of objects with the same value having different memory IDs. As far as I know, In Python, immutable types like integers, and float are indeed passed by value. It is expected that two different integer objects with the same value could have different memory IDs because they are separate objects. However, due to optimization in Python, sometimes the interpreter may treat these objects as the same and assign them the same ID.

If there is nothing wrong with what I wrote above, here is my question. How is it determined whether to apply optimization? Why am I getting different results in the same computer and Python env?

a=5.0
b=5.0

print(a is b)

enter image description here

I tried it in VSCODE and Command Prompt. and I looked for the same question but couldn't see exactly same.

moken
  • 3,227
  • 8
  • 13
  • 23
  • 1
    TL;DR: You can't really have any specific expectations about the behaviour of `is` with literals. – deceze Aug 21 '23 at 05:07
  • 1
    are the python versions you are using, exactly the same? – Mohammad Mostafa Dastjerdi Aug 21 '23 at 05:08
  • The techinque is called interning. I don't think python intern float type objects. If you see the id of`a` and `b` is different – novice Aug 21 '23 at 05:10
  • The python parser does a lot of interning because its relatively cheap as a one-time optimization. I'm not sure what that top tool is, but it likely parsed all of the lines at once so interning happened. The shell in the bottom example parsed line at a time, so didn't intern - but it would have if the same literal was used multiple times in the one line. – tdelaney Aug 21 '23 at 05:14
  • @tdelaney: the tool looks like PyCharm. But why should interning be tool-dependent? It should be Python-dependent, no? – Thomas Weller Aug 21 '23 at 05:16
  • 2
    There is constant argument about what "pass by value" and "pass by reference" means. But python always passes values the same (what I would call pass by reference, beause internally its a pointer to the object). Python never changes values directly. It calls methods on the object to affect a change. The difference is that immutable objects refuse to change themselves. – tdelaney Aug 21 '23 at 05:17
  • 1
    @ThomasWeller - Its python dependent too, but interning in the parser has been around for a very long time. If you run a program in pycharm, its going to run the parser on the entire module, which will naturally intern across the whole module. If you go line by line in a shell, the parser is run for each line, giving few opportunities to get a bunch of references to a single value. – tdelaney Aug 21 '23 at 05:22

0 Answers0