0
votes

I'm using PyCharm 2016.1.3 Community edition.

When the code below is copied to python console as block, variables 'a' and 'b' are the same objects

>>> a = 1000
b = 1000
print (a is b)
True

>>> id(a)
36079236
>>> id(b)
36079236

But in this case, when entering code line by line, both variables are different objects

>>> a = 1000
>>> b = 1000
>>> print (a is b)
False

Could it be that in the first case PyCharm doing some kind of optimization here?

Thanks for help

1

1 Answers

1
votes

No, if you paste that block into a file and run python thefile.py you will see True, but in a plain Python console you will get False from running each line on its own. My guess is that when a block of code is compiled at once, common constants are mapped to the same object, which doesn't happen but when an interactive interpreter receives the lines separately.

Note that this isn't a bug in any sense. It's called interning, and Python does it with small integers (replace 1000 with 5 and you'll get True in both cases) and string literals as well. Other languages such as Java do the same.