difference in binding between strings and tuples?

Alex delete.this.part.alex.news at attbi.com
Tue May 13 17:19:37 EDT 2003


Iwan van der Kleyn wrote:

> I tried to explain a Java minded collegue the concept of name binding or
> variable assignement, straight from Python in a Nutshell. (which by the
> way is, together with the Cookbook a very niece piece of work). But then
> it proved that perhaps I really did not fully grasp all aspects of it
> myself.  Check out:
> 
>  >>> a = 1
>  >>> b = 1
>  >>> a == b
> 1
>  >>> a is b
> 1
>  >>> a += 1
>  >>> b += 1
>  >>> a == b
> 1
>  >>> a is b
> 1
>  >>> x = 'test'
>  >>> y = 'test'
>  >>> x == y
> 1
>  >>> x is y
> 1
>  >>> x += 's'
>  >>> x == y
> 1
>  >>> x is y
> 0
>  >>> q = (0, 1)
>  >>> r = (0, 1)
>  >>> q == r
> 1
>  >>> q is r
> 0
> 
> 
> Ok? Testing for equality gives no suprises, but testing for identity
> does, especially considering the differences between strings and tuples
> (both of which are immutable)
> I had expected  (a is b) == True, even after the addidtion. But how do I
> explain the results for the strings and tuples?
> 
> Can I presume x and y to refer to the same string  object before the
> append ("addition" ) but to two seperate objects afterwards? Why isn't
> that true for the tuples? In other words: why the difference in binding
> between strings and tuples?
> 
> Regards,
> 
> iwan

Should there have been a y += 's' in there somewhere?

I'll venture an uneducated guess:

With strings, if compairson equality implied identity equality, then every
time a new string was created during program execution, python would have
to compare it with every other string.  That would be rather costly. 
Pooling strings while compiling is relatively cheap.

As for tuples, they can consist of heterogeneous items. To pool them python
would have to check that the tuple were of the same size and shape and
check that all the tuple items were immutable and equal.  Probably not
worth the effort.

I'm not clear why one need to use identity comparison on immutable objects
anyway.  The effect you are seeing just strikes me as the inconsequential
side effect of an optimization.

But then again I've only been at this for a few weeks...













More information about the Python-list mailing list