hashval and Numpy

Michael Hudson mwh at python.net
Wed Oct 17 10:07:41 EDT 2001


Uwe Schmitt <uwe at rocksport.de> writes:

> Emile van Sebille <emile at fenx.com> wrote:
> | How about:
> 
> |>>> a
> | array([3, 4])
> |>>> `a`
> | 'array([3, 4])'
> |>>> ky = `Numeric.array((3,4))`
> |>>> ky
> | 'array([3, 4])'
> 
> | Not ideal, but would work in a pinch.  ;-)
> 
> shurely it's possible to assign each array an hashval. this can be
> done by converting an array to a tuple (or a tuple of tuples in the
> 2d case). but: how can i expand numpy, such that a hashval is
> considered.
> i tried 
> 
>      Numeric.array.__hash__ = lambda x: hash(tuple(x))
> 
> but i get
> 
> "object has readonly attributes"....
> 

If that did work, consider (made up interactive session):

>>> a = Numeric.array([1,2])
>>> hash(a)
56
>>> d = {a:1} # a will be in the 56%8-th slot (in 2.2, anyway)
>>> a[0] = 2
>>> hash(a)
57
>>> d[a] # looks in 57%8-th slot - which is empty
KeyError
>>> b = Numeric.array([1,2])
>>> hash(b)
56
>>> d[b] # looks in 56%8-th slot - but what's there is not __eq__ to b!
KeyError

Moral: don't use mutable objects as dictionary keys.

Cheers,
M.

-- 
  Java sucks. [...] Java on TV set top boxes will suck so hard it
  might well inhale people from off  their sofa until their heads
  get wedged in the card slots.              --- Jon Rabone, ucam.chat



More information about the Python-list mailing list