Newbie question: exceptions in Learning Python

Fredrik Lundh fredrik at pythonware.com
Thu May 3 13:43:11 EDT 2001


Leighton Pritchard wrote:

> However, when I run this on Python 2.0 under WindowsNT, I get the
> following:
>
> >>> ex1 = "spam"
> >>> ex2 = "spam"
> >>> ex1 == ex2, ex1 is ex2
> (1, 1)
> >>> ex1
> 'spam'
> >>> ex2
> 'spam'
> >>> ex1 is ex2
> 1

the example depends on an implementation detail.  Python strings
cannot be modified, so the interpreter can safely map both literals
to the same string object if it wants to.

in this case, since the literals look like valid identifiers, Python passes
them through the built-in intern() function [1].

if you change "spam" to "spam+spam", you'll get distinct objects --
at least under the current version of CPython.

Cheers /F

1) this behaviour isn't new in 2.0; iirc, interning was introduced
in one of the 1.5 alpha releases, many years ago.

>>> print intern.__doc__
intern(string) -> string

"Intern" the given string.  This enters the string in the (global)
table of interned strings whose purpose is to speed up dictionary lookups.
Return the string itself or the previously interned string object with the
same value.
>>>





More information about the Python-list mailing list