[pypy-svn] r38167 - in pypy/dist/pypy/objspace: . test

arigo at codespeak.net arigo at codespeak.net
Thu Feb 8 16:38:16 CET 2007


Author: arigo
Date: Thu Feb  8 16:38:14 2007
New Revision: 38167

Modified:
   pypy/dist/pypy/objspace/test/test_thunkobjspace.py
   pypy/dist/pypy/objspace/thunk.py
Log:
Add a thunk space @pypymagic.lazy, to decorate functions that
you want to return a lazy result (the function is really only
called when the result is needed).


Modified: pypy/dist/pypy/objspace/test/test_thunkobjspace.py
==============================================================================
--- pypy/dist/pypy/objspace/test/test_thunkobjspace.py	(original)
+++ pypy/dist/pypy/objspace/test/test_thunkobjspace.py	Thu Feb  8 16:38:14 2007
@@ -84,3 +84,17 @@
             pass
         assert is_thunk(thunk(f))
         assert not is_thunk(42)
+
+    def test_lazy(self):
+        from pypymagic import lazy
+        lst = []
+        def f(x):
+            lst.append(x)
+            return x+5
+        f = lazy(f)
+        y = f(3)
+        assert lst == []
+        assert type(y) is int
+        assert lst == [3]
+        assert type(y) is int
+        assert lst == [3]

Modified: pypy/dist/pypy/objspace/thunk.py
==============================================================================
--- pypy/dist/pypy/objspace/thunk.py	(original)
+++ pypy/dist/pypy/objspace/thunk.py	Thu Feb  8 16:38:14 2007
@@ -1,7 +1,7 @@
 """Example usage:
 
     $ py.py -o thunk
-    >>> from pypymagic import thunk, become
+    >>> from pypymagic import thunk, lazy, become
     >>> def f():
     ...     print 'computing...'
     ...     return 6*7
@@ -16,11 +16,22 @@
     >>> type(y)
     computing...
     <pypy type 'int'>
+
+    >>> @lazy
+    ... def g(n):
+    ...     print 'computing...'
+    ...     return n + 5
+    ...
+    >>> y = g(12)
+    >>> y
+    computing...
+    17
 """
 
 from pypy.objspace.proxy import patch_space_in_place
 from pypy.interpreter import gateway, baseobjspace, argument
 from pypy.interpreter.error import OperationError
+from pypy.interpreter.typedef import Method
 
 # __________________________________________________________________________
 
@@ -85,6 +96,12 @@
     return space.w_None
 app_become = gateway.interp2app(become)
 
+def lazy(space, w_callable):
+    meth = Method(space, space.wrap(app_thunk),
+                  w_callable, space.type(w_callable))
+    return space.wrap(meth)
+app_lazy = gateway.interp2app(lazy)
+
 # __________________________________________________________________________
 
 nb_forcing_args = {}
@@ -161,4 +178,6 @@
                   space.wrap(app_is_thunk))
     space.setattr(w_pypymagic, space.wrap('become'),
                  space.wrap(app_become))
+    space.setattr(w_pypymagic, space.wrap('lazy'),
+                 space.wrap(app_lazy))
     return space



More information about the Pypy-commit mailing list