Commits

Amaury Forgeot d'Arc  committed b8bb27a

Memoryview objects are now hashable.

  • Participants
  • Parent commits b82a4b6
  • Branches py3.3

Comments (0)

Files changed (2)

File pypy/objspace/std/memoryobject.py

 import operator
 
 from rpython.rlib.buffer import Buffer, SubBuffer
+from rpython.rlib.objectmodel import compute_hash
 from pypy.interpreter.baseobjspace import W_Root
 from pypy.interpreter.error import OperationError, oefmt
 from pypy.interpreter.gateway import interp2app
     def __init__(self, buf):
         assert isinstance(buf, Buffer)
         self.buf = buf
+        self._hash = -1
 
     def buffer_w(self, space, flags):
         self._check_released(space)
         else:
             return self.getrepr(space, u'memory')
 
+    def descr_hash(self, space):
+        if self._hash == -1:
+            self._check_released(space)
+            if not self.buf.readonly:
+                raise OperationError(space.w_ValueError, space.wrap(
+                        "cannot hash writable memoryview object"))
+            self._hash = compute_hash(self.buf.as_str())
+        return space.wrap(self._hash)
+
     def descr_release(self, space):
         self.buf = None
 
     __ne__      = interp2app(W_MemoryView.descr_ne),
     __setitem__ = interp2app(W_MemoryView.descr_setitem),
     __repr__    = interp2app(W_MemoryView.descr_repr),
+    __hash__      = interp2app(W_MemoryView.descr_hash),
     __enter__   = interp2app(W_MemoryView.descr_enter),
     __exit__    = interp2app(W_MemoryView.descr_exit),
     __weakref__ = make_weakref_descr(W_MemoryView),

File pypy/objspace/std/test/test_memoryobject.py

         assert repr(memoryview(b'hello')).startswith('<memory at 0x')
 
     def test_hash(self):
-        raises(TypeError, "hash(memoryview(b'hello'))")
+        assert hash(memoryview(b'hello')) == hash(b'hello')
 
     def test_weakref(self):
         import weakref