Tuple Semantics - Rationale'?
Quinn Dunkan
quinn at yak.ugcs.caltech.edu
Wed Jul 11 18:44:54 EDT 2001
On Wed, 11 Jul 2001 21:40:52 GMT, Nick Perkins <nperkins7 at home.com> wrote:
>
>"Quinn Dunkan" <quinn at yak.ugcs.caltech.edu> wrote in message
>"""
>Large complicated data structures of nested tuples might be a mistake.
>Tuples
>and python's simple pattern matching can be handy for small ad hoc types,
>but
>don't forget about classes.
>"""
>
>Yes,
>...but I have found one good use for such 'tuple gymnastics'.
>( perhaps this is what you mean by 'pattern matching' )
No, what I mean by that is what python calls "tuple unpacking". For instance:
t = ((green, (10, 20), 1),
(blue, (20, 30), 0),
(green, (40, 20), 1))
for (color, (x, y), active) in t:
...
def display((color, (x, y), active)):
...
map(display, t)
might be quicker and clearer than throwing together some class for the same.
Although some might disagree about that 'def' line (and I might be one of them
<wink>).
>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
>key.
In this case I'd write __hash__ and __cmp__ methods and stuff the objects
directly into the dict.
>example:
>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>
>>> class Point:
... def __init__(self, x, y):
... self.x = x
... self.y = y
... def __hash__(self):
... return hash((self.x, self.y))
... def __cmp__(self, other):
... return cmp((self.x, self.y), (other.x, other.y))
...
>>> p1 = Point(3, 4)
>>> p2 = Point(3, 4)
>>> color = {}
>>> color[p1] = 'red'
>>> color[p2]
'red'
>>>
More information about the Python-list
mailing list