From: Stefan Behnel Date: Thu, 16 Dec 2010 23:42:12 +0000 (+0100) Subject: extended test case for nonlocal X-Git-Url: http://git.tremily.us/?a=commitdiff_plain;h=f39afe8d6816c146eeb0bdc0708787961d6ffb79;p=cython.git extended test case for nonlocal --- diff --git a/tests/run/nonlocal_T490.pyx b/tests/run/nonlocal_T490.pyx index cd2d26b7..c80c1808 100644 --- a/tests/run/nonlocal_T490.pyx +++ b/tests/run/nonlocal_T490.pyx @@ -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