"/a" is not "/a" ?
Gary Herron
gherron at islandtraining.com
Fri Mar 6 14:46:14 EST 2009
Emanuele D'Arrigo wrote:
> Hi everybody,
>
> while testing a module today I stumbled on something that I can work
> around but I don't quite understand.
>
*Do NOT use "is" to compare immutable types.* **Ever! **
It is an implementation choice (usually driven by efficiency considerations) to choose when two strings with the same value are stored in memory once or twice. In order for Python to recognize when a newly created string has the same value as an already existing string, and so use the already existing value, it would need to search *every* existing string whenever a new string is created. Clearly that's not going to be efficient. However, the C implementation of Python does a limited version of such a thing -- at least with strings of length 1.
Gary Herron
>
>>>> a = "a"
>>>> b = "a"
>>>> a == b
>>>>
> True
>
>>>> a is b
>>>>
> True
>
>
>>>> c = "/a"
>>>> d = "/a"
>>>> c == d
>>>>
> True # all good so far
>
>>>> c is d
>>>>
> False # eeeeek!
>
> Why c and d point to two different objects with an identical string
> content rather than the same object?
>
> Manu
> --
> http://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list