3

I am aware of the difference of 'is' operator with strings. However, when I type the following example in Pycharm I get always True.

a = 'a monkey'
b = 'a monkey'
print(a is b)

I get:

True

Where in terminal:

>>> a = 'a monkey'
>>> b = 'a monkey'
>>> a is b
False

Why is this happening?

Edit: Why Pycharm returns always True?

Tasos Tsournos
  • 314
  • 2
  • 9
  • 1
    So, you are not "aware of the difference of 'is' operator with strings"? Especially not that you use `==` for string comparison, not `is`. – Klaus D. Oct 15 '19 at 08:46
  • I am aware that one should not compare immutable objects with 'is'. My question is why Pycharm always returns True. – Tasos Tsournos Oct 15 '19 at 08:55
  • I think the shell is running each line of the input as a separate process - so the interning is not happening. Because when I do this: `a = 'a monkey'; b = 'a monkey'; print(a is b)` I get `True` – rdas Oct 15 '19 at 08:56
  • 3
    [Bytecode compiler optimization behavior.](https://stackoverflow.com/a/35276097/2357112) Never rely on it. It's different in different implementations and subject to change without notice. – user2357112 Oct 15 '19 at 08:58
  • I think, the above could be the answer, which could explain why it behaves differently in `pycharm` and in `shell`. Apologies for the premature answer – han solo Oct 15 '19 at 09:00
  • Thank you for your answer. New knowledge acquired – Tasos Tsournos Oct 15 '19 at 09:02

0 Answers0