[pypy-commit] pypy hpy: implement a context-manager to allocate handles

antocuni pypy.commits at gmail.com
Sat Nov 16 19:16:22 EST 2019


Author: Antonio Cuni <anto.cuni at gmail.com>
Branch: hpy
Changeset: r98090:1dc8e3639eb3
Date: 2019-11-17 01:00 +0100
http://bitbucket.org/pypy/pypy/changeset/1dc8e3639eb3/

Log:	implement a context-manager to allocate handles

diff --git a/pypy/module/hpy_universal/handles.py b/pypy/module/hpy_universal/handles.py
--- a/pypy/module/hpy_universal/handles.py
+++ b/pypy/module/hpy_universal/handles.py
@@ -38,6 +38,10 @@
     mgr = space.fromcache(HandleManager)
     return mgr.new(w_object)
 
+def close(space, index):
+    mgr = space.fromcache(HandleManager)
+    mgr.close(index)
+    
 def consume(space, index):
     mgr = space.fromcache(HandleManager)
     return mgr.consume(index)
@@ -45,3 +49,21 @@
 def dup(space, index):
     mgr = space.fromcache(HandleManager)
     return mgr.dup(index)
+
+
+class using(object):
+    """
+    context-manager to new/close a handle
+    """
+
+    def __init__(self, space, w_object):
+        self.space = space
+        self.w_object = w_object
+        self.h = -1
+
+    def __enter__(self):
+        self.h = new(self.space, self.w_object)
+        return self.h
+
+    def __exit__(self, etype, evalue, tb):
+        close(self.space, self.h)
diff --git a/pypy/module/hpy_universal/test/test_handles.py b/pypy/module/hpy_universal/test/test_handles.py
--- a/pypy/module/hpy_universal/test/test_handles.py
+++ b/pypy/module/hpy_universal/test/test_handles.py
@@ -1,3 +1,4 @@
+from pypy.module.hpy_universal import handles
 from pypy.module.hpy_universal.handles import HandleManager
 
 class TestHandleManager(object):
@@ -35,3 +36,14 @@
         h1 = mgr.dup(h0)
         assert h1 != h0
         assert mgr.consume(h0) == mgr.consume(h1) == 'hello'
+
+def test_using():
+    mgr = HandleManager(None)
+    class FakeSpace(object):
+        @classmethod
+        def fromcache(cls, x):
+            return mgr
+    space = FakeSpace()
+    with handles.using(space, 'hello') as h:
+        assert mgr.handles_w[h] == 'hello'
+    assert mgr.handles_w[h] is None


More information about the pypy-commit mailing list