difference in binding between strings and tuples?

Donn Cave donn at u.washington.edu
Tue May 13 17:01:08 EDT 2003


Quoth Iwan van der Kleyn <null at null.com>:
| 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

You should also try this with other integer values - start with 20407
and increment by 123409, for example.  Then "is" will be false.
What you are seeing is not a fundamental consequence of Python's
name binding system, it's a cache of certain types of values.  Small
integers, small strings, etc.


|  >>> x = 'test'
|  >>> y = 'test'
|  >>> x == y
| 1
|  >>> x is y
| 1
|  >>> x += 's'
|  >>> x == y
| 1
|  >>> x is y
| 0

Now you are looking at the effect of +=.  Did you mean to also
increment y?  Oh well, the result would have been the same!
I don't know, perhaps the small-string cache is used for literals
only.

|  >>> 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?

There apparently is no cache for 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?

It would be safest not to expect any two values to be identical (in the
"is" sense) unless they're directly related by reference, but not to
expect them _not_ to be identical unless they are mutable (because
Python will never cache mutable objects like that.)

Note also that += may rebind the left hand side or may not, depends.
Like the caching thing, it may confuse the issue more than it helps.

	Donn Cave, donn at u.washington.edu




More information about the Python-list mailing list