Python name lookups / Interning strings
Terry Hancock
hancock at anansispaceworks.com
Tue Oct 11 21:17:08 EDT 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
like:
>>> a = "A"
>>> b = "A"
will result not only in:
>>> a == b
True
but also
>>> a is b
True
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
True
>>> a is b
False
Now, however, 'a==b' must do an actual string comparison,
and is therefore somewhat slower.
--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks http://www.anansispaceworks.com
More information about the Python-list
mailing list