Commit f39afe8d authored by Stefan Behnel's avatar Stefan Behnel

extended test case for nonlocal

parent d8813f05
...@@ -64,3 +64,108 @@ def argtype(int n): ...@@ -64,3 +64,108 @@ def argtype(int n):
print n print n
return 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
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment