Why are tuples immutable?

Roy Smith roy at panix.com
Fri Dec 17 23:23:17 EST 2004


In article <10s6se2m73b47f5 at corp.supernews.com>,
 Jeff Shannon <jeff at ccvcorp.com> wrote:

> Roy Smith wrote:
> >All that's needed is to define __hash__() and __cmp__() methods which
> >only look at some subset of the object's data atrributes.  You can
> >keep those attributes constant (perhaps enforced with __setattr__()
> >hooks) and let others mutate.
> 
> In which case, one could argue that your __cmp__() is not fulfilling the 
> semantics of mathematical equality, because even though the objects 
> compare the same, they are not interchangeable.  (They may be "close 
> enough to equal for this particular purpose", but that's a different 
> thing regardless of whether or not it's useful in practice.)

I'm not sure what "mathematical equality" means, but we're not talking 
math here, we're talking programming.  Or at least I am :-)  What better 
definition of "equality" in a programming language could there be other 
than the == operator returns true?

I'm also not sure what you mean by "interchangeable".  Are 1 and 1.0 
interchangeable?  They're equal:

>>> 1 == 1.0
True

They hash the same:

>>> hash (1)
1
>>> hash (1.0)
1

They work the same as a dictionary key:

>>> d = {}
>>> d [1] = "one"
>>> d [1.0]
'one'

They don't act the same in other respects, though:

>>> 1 / 2
0
>>> 1.0 / 2
0.5

Are they "interchangeable"?  Beats me.  I guess it depends on how you 
define "interchangeable".  I know Python defines equality (==) and 
identity (is), but I don't believe it defines interchangeability.

If I give you a $100 bill, and you give me back a different $100 bill, 
are the two bills equal?  They may have different serial numbers, but 
for any financial purpose, they're equal.  Are they interchangeable?  I 
think most people would argue they are.  But that's only because most 
people's definition of equality for money only deals with monetary 
value, and ignores other attributes of the banknote such as date of 
issue and serial number.

> It is possible to create mutable objects for which one can arrange 
> things so that they can act like they're hashable.  Unless I'm 
> completely mistaken about the mathematical principles involved, however, 
> then the mathematics implied by the terms "hash function" and "equality" 
> cannot be universally fulfilled by mutable objects.

Again, all I can say is we're not talking about some abstract 
mathematical concept, we're talking about objects in a programming 
environment.  Hash is not a "mathematical principle", it's a function 
you can call to get a result.



More information about the Python-list mailing list