0

Consider the two scenarios:

>>> a = "python is cool!"
>>> b = "python is cool!"
>>> a is b
False

and

>>> a = "python"
>>> b = "python"
>>> a is b
True   # a and b refer to the same object!

I am wondering why string interning occurs in the second scenario but not the first. Is is due to the exclamation mark or the general length? Thanks!

nemequ
  • 16,623
  • 1
  • 43
  • 62
user321627
  • 2,350
  • 4
  • 20
  • 43
  • I fail to see how having an exclamation mark induces difference objects. I do understand that the "is" operator compares objects, but what is it about the exclamation mark that changes this? If I removed the exclamation mark from the first chunk of code, it evaluates as true! – user321627 Sep 30 '18 at 07:19
  • Is a space the same thing as an exclamation mark? – user321627 Sep 30 '18 at 07:20
  • Removing the exclamation mark wouldn't be enough to trigger interning in CPython. You most likely did something else different in the exclamation-mark-removed case to trigger a different optimization, bytecode constant deduplication, which looks a lot like interning but is a different mechanism. – user2357112 Sep 30 '18 at 07:22
  • Possible candidates would be putting the assignments on the same line or putting the code in a script or a function. – user2357112 Sep 30 '18 at 07:23

0 Answers0