I just started using numpy and its matrix module (very very useful!), And I wanted to use a matrix object as a dictionary key, so I checked if matrix t23> had:
>>> from numpy import matrix >>> hasattr(matrix, '__hash__') True
And so it is! Nice, so this means that it can be a dictionary key:
>>> m1 = matrix('1 2 3; 4 5 6; 7 8 9') >>> m1 matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> m2 = matrix('1 0 0; 0 1 0; 0 0 1') >>> m2 matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) >>> matrix_dict = {m1: 'first', m2: 'second'}
Works! Now let's continue testing:
>>> matrix_dict[m1] 'first' >>> matrix_dict[matrix('1 2 3; 4 5 6; 7 8 9')] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
What? So it works for the same matrix, but it doesn't work for another matrix with exactly the same content? Let's see what __hash__ returns:
>>> hash(m1) 2777620 >>> same_as_m = matrix('1 2 3; 4 5 6; 7 8 9') >>> hash(same_as_m) -9223372036851998151 >>> hash(matrix('1 2 3; 4 5 6; 7 8 9'))
So, the __hash__ matrix from numpy method returns different values ββfor the same matrix .
Is it correct? Does this mean that it cannot be used as a dictionary key? And if it cannot be used, why did it implement __hash__ ?