string identity and comparison

bruno.desthuilliers at gmail.com bruno.desthuilliers at gmail.com
Thu Dec 16 07:06:12 EST 2010


On 16 déc, 12:55, Jean-Michel Pichavant <jeanmic... at sequans.com>
wrote:
> Fellows,
>
> I'd like to illutrate the fact that comparing strings using identity is,
> most of the time, a bad idea. However I'm searching a short example of
> code that yields 2 differents object for the same string content.
>
> id('foo')
> 3082385472L
> id('foo')
> 3082385472L
>
> Anyone has that kind of code ?

2 points:


1- an id is only valid for the lifetime of a given object - when the
object has been collected, the id can be reused for another object.

2- in CPython, strings that would be valid Python identifiers are
interned. Try using a string that would not be a valid Python
identifier

Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> id("Not a valid python identifier")
3076522016L
>>> id("Not a valid python identifier")
3076522016L
>>> s1 = "Not a valid python identifier"
>>> s2 = "Not a valid python identifier"
>>> s1 is s2
False
>>> s1 == s2
True
>>>


HTH



More information about the Python-list mailing list