tuples are useless???

James Stroud jstroud at mbi.ucla.edu
Mon Apr 9 01:20:45 EDT 2007


Steven D'Aprano wrote:
> On Mon, 09 Apr 2007 02:26:37 +0000, James Stroud wrote:
> 
>> Bart Willems wrote:
>>> James Stroud wrote:
>>>> ... It boils down to the fact that tuples are useless as a result 
>>>> unless you know you really need them--and you never really NEED them.
>>> Could you clarify that for me? I use tuples *a lot* and I really *NEED* 
>>> them - I'm building a lot of multi-tier reports where detail-level data 
>>> is pulled out of a dictionary based on a composed key. It is impossible 
>>> to build those dictionaries *without* using tuples.
>>
>> "Impossible" is a strong word, as is "need" (especially when in all caps).
>>
>> py> import md5
>> py> class HashedList(list):
>> ...   def __hash__(self):
>> ...     h = md5.new()
>> ...     for item in self:
>> ...       h.update(str(hash(item)))
>> ...     return int(h.hexdigest(), 16)
>> ...
>> py> hl = HashedList('bob', 'carol', 'ted')
>> py> {hl:3}
>> {['bob', 'carol', 'ted']: 3}
>>
>> Impossible? I wouldn't even say that this was all that difficult.
> 
> Possible, if by possible you mean "broken".
> 
> 
>>>> D = {hl: 3}
>>>> D
> {['bob', 'carol', 'ted']: 3}
>>>> hl[0] = 'Bob'
>>>> D
> {['Bob', 'carol', 'ted']: 3}
>>>> D.keys()[0] is hl
> True
>>>> D[hl]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> KeyError: ['Bob', 'carol', 'ted']
> 
> 

   def __setitem__(self, *args):
     raise TypeError, '%s doesn't support item assignment.' % 
self.__class__.__name__


Problem fixed. Next?

By the way, this would be analagous to the tedious

class Something(object):
   def __init__(self, value):
     self._value = value
   value = property(lambda: self._value)

just to make sure users don't change the value of value so they don't 
"break" the instance.

I don't think Bart is changing the items in his keys anyway--so the 
problem which was stated as impossible is still possible. The solution 
was not to code to your personal expectations but to show how tuples are 
never essential. Any number of solutions could fix the problem you have 
invented.

James



More information about the Python-list mailing list