Why are tuples immutable?

Roy Smith roy at panix.com
Thu Dec 16 11:29:32 EST 2004


Adam DePrince  <adam at cognitcorp.com> wrote:
> And how exactly do you propose to mutate an object without
> changing its hash value?

That's easy.  Define a hash function that doesn't use all the data in
the object.

class Foo:
      def __init__ (self, a, b, c):
	  self.a = a
          self.b = b
	  self.c = c

      def __hash__ (self):
	  return (self.a + self.b)

You can now alter a Foo's c attribute without changing its hash.  To
really make the above class work right, you need to define __cmp__(),
but this illustrates the point.

In C++, this concept is expressed by the mutable keyword.  You can
have a const object and still be able to change its mutable members.

Imagine I'm building a real estate database.  My Property class stores
block, lot, and zoning.  I might very well want to hash
and compare based on just block and lot, because those are the things
which identify which piece of real estate I'm talking about.  Maybe
something like:

# Demo purposes only; untested code
class Property:
    def __init__ (self, block, lot, zoning="Unknown"):
        self.block = block
        self.lot = lot
        self.zoning = zoning

    def __hash__ (self):
        return (self.block + self.lot)

    def __cmp__ (self, other):
	# I wish there was a less verbose way to do this!
        if self.block < other.block:
            return -1
        if self.block > other.block:
            return 1
        if self.lot < other.lot:
            return -1
        if self.lot > other.lot:
            return 1
        return 0

Then I could do something like:

p1 = Property (123, 5, "Residential")
ownerDict [p1] = "Roy Smith"
print ownerDict [Property (123, 5)]    # prints my name
p1.zoning = "Commercial"
print ownerDict [Property (123, 5)]    # still prints my name



More information about the Python-list mailing list