Tuple Semantics - Rationale'?

Nick Perkins nperkins7 at home.com
Wed Jul 11 23:40:52 CEST 2001

"Quinn Dunkan" <quinn at yak.ugcs.caltech.edu> wrote in message
Large complicated data structures of nested tuples might be a mistake.
and python's simple pattern matching can be handy for small ad hoc types,
don't forget about classes.

...but I have found one good use for such 'tuple gymnastics'.
( perhaps this is what you mean by 'pattern matching' )

When you want to have a dictionary that uses some type of object as a key,
but you want 'identical' objects to considered 'the same', you can pack the
relevant bits of an instance's data into a tuple, and use it as the dict

Suppose you want to keep track of the color any given x,y point...

>>> class point:
...  def __init__(self,x,y):
...   self.x = x
...   self.y = y
...  def as_tuple(self):
...   return (self.x,self.y)
>>> p1 = point(3,4)
>>> p2 = point(3,4)
>>> color = {}
>>> color[p1]='red'
>>> color[p2]
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
KeyError: <__main__.point instance at 01373A6C>

# not the same instance

>>> color[p1.as_tuple()]='red'
>>> color[p2.as_tuple()]

# ..but the generated tuples are considered the same

This example is trivial, but I have used the same technique for much more
complicated objects, often generating a 'stucture of tuples', much like the
original poster was using.  Such a structure is, of course, unweildy, but it
makes a great dictionary key!  You can pick and choose which bits of
instance data to include, depending on your needs.  I have used this to
detect the (unwanted) generation of multiple, similar objects.  And the good
news is that you never have to manually extract info from the tuple, at all.

Another variation is to keep a dict which maps the tuple back to the object
itself, if that suits your needs.

More information about the Python-list mailing list