[Python-Dev] Hashable memoryviews

Stefan Krah stefan at bytereef.org
Sun Nov 13 11:39:46 CET 2011


Antoine Pitrou <solipsis at pitrou.net> wrote:
> Only if the original object is itself mutable, otherwise the memoryview
> is read-only.
> 
> I would propose the following algorithm:
> 1) try to calculate the original object's hash; if it fails, consider
>    the memoryview unhashable (the buffer is probably mutable)

With slices or the new casts (See: http://bugs.python.org/issue5231,
implemented in http://hg.python.org/features/pep-3118#memoryview ),
it is possible to have different hashes for equal objects:

>>> b1 = bytes([1,2,3,4])
>>> b2 = bytes([4,3,2,1])
>>> m1 = memoryview(b1)
>>> m2 = memoryview(b2)[::-1]
>>> m1 == m2
True
>>> hash(b1)
4154562130492273536
>>> hash(b2)
-1828484551660457336


Or:

>>> a = array.array('L', [0])
>>> b = b'\x00\x00\x00\x00\x00\x00\x00\x00'
>>> m_array = memoryview(a)
>>> m_bytes = memoryview(b)
>>> m_cast = m_array.cast('B')
>>> m_bytes == m_cast
True
>>> hash(b) == hash(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'array.array'


Stefan Krah




More information about the Python-Dev mailing list