[pypy-commit] pypy py3k: Context manager for mmap.

amauryfa noreply at buildbot.pypy.org
Sat Oct 20 07:00:30 CEST 2012


Author: Amaury Forgeot d'Arc <amauryfa at gmail.com>
Branch: py3k
Changeset: r58266:055710da332e
Date: 2012-10-20 06:59 +0200
http://bitbucket.org/pypy/pypy/changeset/055710da332e/

Log:	Context manager for mmap.

diff --git a/pypy/module/mmap/interp_mmap.py b/pypy/module/mmap/interp_mmap.py
--- a/pypy/module/mmap/interp_mmap.py
+++ b/pypy/module/mmap/interp_mmap.py
@@ -1,6 +1,6 @@
 from pypy.interpreter.error import OperationError, wrap_oserror
 from pypy.interpreter.baseobjspace import Wrappable
-from pypy.interpreter.typedef import TypeDef
+from pypy.interpreter.typedef import TypeDef, GetSetProperty
 from pypy.interpreter.gateway import interp2app, unwrap_spec
 from pypy.rlib import rmmap, rarithmetic
 from pypy.rlib.rmmap import RValueError, RTypeError
@@ -132,6 +132,13 @@
     def __len__(self):
         return self.space.wrap(self.mmap.size)
 
+    def closed_get(self, space):
+        try:
+            self.mmap.check_valid()
+        except RValueError:
+            return space.w_True
+        return space.w_False
+
     def check_valid(self):
         try:
             self.mmap.check_valid()
@@ -199,6 +206,14 @@
         space = self.space
         return space.wrap(StringLikeBuffer(space, space.wrap(self)))
 
+    def descr_enter(self, space):
+        self.check_valid()
+        return space.wrap(self)
+
+    def descr_exit(self, space, __args__):
+        self.close()
+
+
 if rmmap._POSIX:
 
     @unwrap_spec(fileno=int, length=int, flags=int,
@@ -260,6 +275,10 @@
     __getitem__ = interp2app(W_MMap.descr_getitem),
     __setitem__ = interp2app(W_MMap.descr_setitem),
     __buffer__ = interp2app(W_MMap.descr_buffer),
+    __enter__ = interp2app(W_MMap.descr_enter),
+    __exit__ = interp2app(W_MMap.descr_exit),
+
+    closed = GetSetProperty(W_MMap.closed_get),
 )
 
 constants = rmmap.constants
diff --git a/pypy/module/mmap/test/test_mmap.py b/pypy/module/mmap/test/test_mmap.py
--- a/pypy/module/mmap/test/test_mmap.py
+++ b/pypy/module/mmap/test/test_mmap.py
@@ -622,6 +622,12 @@
             finally:
                 m.close()
 
+    def test_context_manager(self):
+        import mmap
+        with mmap.mmap(-1, 10) as m:
+            assert not m.closed
+        assert m.closed
+
     def test_all(self):
         # this is a global test, ported from test_mmap.py
         import mmap


More information about the pypy-commit mailing list