Python name lookups / Interning strings

Terry Hancock hancock at
Wed Oct 12 03:17:08 CEST 2005

On Tuesday 11 October 2005 05:36 pm, Dave wrote:
> What exactly does it mean to "intern" a string?

For very simple strings such as "A" and for strings
used as identifiers (I think), Python creates a permanent
object during byte-code compilation.  Thereafter, any
time that string value occurs in the program, it will
actually be interpreted as a reference to the interned
string object with that value.

So, if for example, "A" is interned, then statements

>>> a = "A"
>>> b = "A"

will result not only in:

>>> a == b

but also

>>> a is b

Note that since 'a is b' always implies 'a == b', the
interpreter needn't do a full value comparison of interned
strings, it can stop when it sees they are references
to the same object.

Whereas, for an un-interned string:

>>> a = "I don't think Python will intern this string."
>>> b = "I don't think Python will intern this string."
>>> a==b
>>> a is b

Now, however, 'a==b' must do an actual string comparison,
and is therefore somewhat slower.

Terry Hancock ( hancock at )
Anansi Spaceworks

More information about the Python-list mailing list