0

I'm using python 2.7.2 with built-in IDLE on windows 7 x64, and found a very strange thing:

>>> a = "aaa"
>>> b = "aaa"
>>> print a is b
True
>>> print a == b
True
>>> print "%s , %s" % (id(a), id(b))
43872224 , 43872224
>>> 

This is normal, but, if the string contains a space:

>>> x = "x x"
>>> y = "x x"
>>> print x is y
False
>>> print x == y
True
>>> print "%s , %s" % (id(x), id(y))
43872008 , 43872128
>>> 

Notice x is y is False! And they have different ids!

I tried these code in PyCharm, everything returns True, so I think this is may be a bug of IDLE.

Isn't it? Or do I miss something?

Freewind
  • 193,756
  • 157
  • 432
  • 708

2 Answers2

3

Python's is operator actually checks to see if the parameters it's passed are the same object, so in this case whilst they are the same value they're not the same object.

This has actually been discussed here before: with a lot more detail as well, worth checking out.

Community
  • 1
  • 1
Nicholas Smith
  • 11,642
  • 6
  • 37
  • 55
  • But it all prints `True` in pycharm, why not IDLE? – Freewind Feb 20 '12 at 12:53
  • Without being a total Python expert (I know enough to get by), I'd say it's possibly a case of PyCharm doing some clever optimisations to try minimise memory foot print, so IDLE itself creates an entirely new object for the two variables, whereas PyCharm sees that the variable has been used before and reuses it to stop another object from being created. – Nicholas Smith Feb 20 '12 at 12:55
  • 1
    @Freewind The shorter and more useful answer is: It's an implementation detail, period. –  Feb 20 '12 at 12:57
2

All that this means is that IDLE implements different string interning policies than the interpreter's, or PyCharm's, defaults. If the strings are interned, then two equal strings will be the same string - ie, a == b will imply a is b. If they are not, then you can have the former without the latter, much like with other python objects:

>>> a = ['']
>>> b = ['']
>>> a is b
False
>>> a == b
True

EDIT: As far as I can tell by experimenting, the interactive interpreter does not interning these strings. However, running it as a .py script does intern them. This is most likely Python treating strings read from STDIN or a disk file differently to string literals in a source code file.

lvc
  • 34,233
  • 10
  • 73
  • 98