string identity and comparison

bruno.desthuilliers at gmail.com bruno.desthuilliers at gmail.com
Thu Dec 16 10:43:41 EST 2010


On 16 déc, 15:53, Jean-Michel Pichavant <jeanmic... at sequans.com>
wrote:
> Mel wrote:
> > Jean-Michel Pichavant 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 ?
>
> > Currently, CPython interns strings that look like identifiers.  Any strings
> > that don't look like identifiers are on their own:
>
> > mwilson at tecumseth:~/sandbox/candlekit/stringlight-1$ python
> > Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
> > [GCC 4.4.3] on linux2
> > Type "help", "copyright", "credits" or "license" for more information.
>
> >>>> a = 'x(3)'
> >>>> id(a)
>
> > 3075373248L
>
> >>>> c='x(3)'
> >>>> id(c)
>
> > 3075373856L
>
> >>>> a==c
>
> > True
>
> >    Mel.
>
> thanks to all who replied.
>
> It looks like there are some differences between python 2.5 & 2.6, I
> tested all the possibilities I've been given in this thread and did not
> always get the same result.

Which FWIW is one more reason to avoid identity testing on strings -
too much implementation specific stuff happening here.




More information about the Python-list mailing list