extended test case for nonlocal
authorStefan Behnel <scoder@users.berlios.de>
Thu, 16 Dec 2010 23:42:12 +0000 (00:42 +0100)
committerStefan Behnel <scoder@users.berlios.de>
Thu, 16 Dec 2010 23:42:12 +0000 (00:42 +0100)
tests/run/nonlocal_T490.pyx

index cd2d26b7c095615d2f78a5e1fe724d7704cbfd64..c80c18083b0d0c44576ebfe5c1ed7ea32db82a81 100644 (file)
@@ -64,3 +64,108 @@ def argtype(int n):
     print n
     return
 
+def ping_pong():
+    """
+    >>> f = ping_pong()
+    >>> inc, dec = f(0)
+    >>> inc()
+    1
+    >>> inc()
+    2
+    >>> dec()
+    1
+    >>> inc()
+    2
+    >>> dec()
+    1
+    >>> dec()
+    0
+    """
+    def f(x):
+        def inc():
+            nonlocal x
+            x += 1
+            return x
+        def dec():
+            nonlocal x
+            x -= 1
+            return x
+        return inc, dec
+    return f
+
+def methods():
+    """
+    >>> f = methods()
+    >>> c = f(0)
+    >>> c.inc()
+    1
+    >>> c.inc()
+    2
+    >>> c.dec()
+    1
+    >>> c.dec()
+    0
+    """
+    def f(x):
+        class c:
+            def inc(self):
+                nonlocal x
+                x += 1
+                return x
+            def dec(self):
+                nonlocal x
+                x -= 1
+                return x
+        return c()
+    return f
+
+# FIXME: doesn't currently work in class namespace:
+
+## def class_body():
+##     """
+##     >>> c = f(0)
+##     >>> c.get()
+##     1
+##     >>> c.x     #doctest: +ELLIPSIS
+##     Traceback (most recent call last):
+##     AttributeError: ...
+##     """
+##     def f(x):
+##         class c:
+##             nonlocal x
+##             x += 1
+##             def get(self):
+##                 return x
+##         return c()
+
+def generator():
+    """
+    >>> g = generator()
+    >>> list(g(5))
+    [2, 3, 4, 5, 6]
+    """
+    def f(x):
+        def g(y):
+            nonlocal x
+            for i in range(y):
+                x += 1
+                yield x
+        return g
+    return f(1)
+
+def nested_nonlocals(x):
+    """
+    >>> g = nested_nonlocals(1)
+    >>> h = g()
+    >>> h()
+    3
+    """
+    def g():
+        nonlocal x
+        x -= 2
+        def h():
+            nonlocal x
+            x += 4
+            return x
+        return h
+    return g