[Tutor] When are strings interned?

Lie Ryan lie.1296 at gmail.com
Fri Jul 3 16:57:48 CEST 2009


Angus Rodgers wrote:
> Presumably a different optimisation is going on here:
> 
>>>> "green ideas" is "green ideas"
> True

You're correct, there is another layer of optimization, now related to
constant string caching. The caching sometimes happens, sometimes not,
depending on a very intricate implementation detail. It's difficult to
explain, better see it yourself.

Regard the following interpreter session as a lesson to not bother on
implementation details:

Python 2.6.2 (r262:71600, Jun 12 2009, 06:02:06)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 'foo bar'
>>> b = 'foo bar'
>>> a is b
False
>>> def foo():
...     c = 'foo bar'
...     print a is c
...     print b is c
...
>>> foo()
False
False
>>> # OK, so is it always False?
... # Think again...
...
>>> def foo():
...     d = 'foo bar'
...     e = 'foo bar'
...     print d is e
...
>>> foo()
True
>>> exit()
$ cat test.py
a = 'foo bar'
b = 'foo bar'
print a is b
$ python test.py
True
$ # wasn't the same test False in the interactive
$ # interpreter earlier?
$ python
Python 2.6.2 (r262:71600, Jun 12 2009, 06:02:06)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 'foo bar'
>>> b = 'foo bar'
>>> a is b
False
>>> # since a is b is equivalent to 'foo bar' is 'foo bar'.
... # And it is False, then this should also be False:
...
>>> 'foo bar' is 'foo bar'
True
>>> # it seems not...

I've only started with 'foo bar'. It is easy to continue further on with
many other oddities involving long strings without spaces, other
immutables, etc, etc, etc.


> [Does it create confusion to quote a dialogue with the interpreter
> in this way?  The >>> looks like an instance of e-mail quotation.]
> 
>> And... have I told you not to rely on this behavior? NEVER rely on this
>> implementation details. Once you get bitten by it, you'll regret it.
> 
> Noted!

Oh, need I to remind that never to rely on any of this behaviors.



More information about the Tutor mailing list