fix 'nonlocal' for class scope
authorStefan Behnel <scoder@users.berlios.de>
Fri, 17 Dec 2010 00:15:19 +0000 (01:15 +0100)
committerStefan Behnel <scoder@users.berlios.de>
Fri, 17 Dec 2010 00:15:19 +0000 (01:15 +0100)
Cython/Compiler/Symtab.py
tests/run/nonlocal_T490.pyx

index 5bbad5072ae3277077a3eb78aa2bef211db219ae..40fb6d48aee92703089f9c54d67d4eecab39df95 100644 (file)
@@ -1450,6 +1450,17 @@ class PyClassScope(ClassScope):
         entry.is_pyclass_attr = 1
         return entry
 
+    def declare_nonlocal(self, name, pos):
+        # Pull entry from outer scope into local scope
+        if self.lookup_here(name):
+            warning(pos, "'%s' redeclared" % name, 0)
+        else:
+            entry = self.lookup(name)
+            if entry is None:
+                error(pos, "no binding for nonlocal '%s' found" % name)
+            else:
+                self.entries[name] = entry
+
     def add_default_value(self, type):
         return self.outer_scope.add_default_value(type)
 
index c80c18083b0d0c44576ebfe5c1ed7ea32db82a81..eb7f6610c77d54fa75272882a8ea021c1b6afc87 100644 (file)
@@ -119,24 +119,25 @@ def methods():
         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 class_body(int x, y):
+    """
+    >>> c = class_body(2,99)
+    >>> c.z
+    (3, 2)
+    >>> c.x     #doctest: +ELLIPSIS
+    Traceback (most recent call last):
+    AttributeError: ...
+    >>> c.y     #doctest: +ELLIPSIS
+    Traceback (most recent call last):
+    AttributeError: ...
+    """
+    class c(object):
+        nonlocal x
+        nonlocal y
+        y = 2
+        x += 1
+        z = x,y
+    return c()
 
 def generator():
     """