Skip to content

Commit ab9cbc8

Browse files
committed
state retention
1 parent cb02363 commit ab9cbc8

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

state_retention.py

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#!/usr/bin/env python3
2+
from __future__ import print_function
3+
4+
5+
# nonlocal 3.x
6+
def tester(start):
7+
state = start
8+
9+
def nested(label):
10+
nonlocal state
11+
print(label, state)
12+
state += 1
13+
return nested
14+
15+
16+
# nested global 2.x, 3.x
17+
def tester1(start):
18+
global gstate
19+
gstate = start
20+
21+
def nested(label):
22+
global gstate
23+
print(label, gstate)
24+
gstate += 1
25+
return nested
26+
27+
28+
# with mutables
29+
def tester2(start):
30+
state = [start]
31+
32+
def nested(label):
33+
print(label, state[0])
34+
state[0] += 1
35+
return nested
36+
37+
38+
# function attr
39+
def tester3(start):
40+
41+
def nested(label):
42+
print(label, nested.state)
43+
nested.state += 1
44+
nested.state = 0
45+
return nested
46+
47+
48+
# class
49+
class tester4(object):
50+
51+
def __init__(self, start):
52+
self.state = start
53+
54+
def __call__(self, label):
55+
print(label, self.state)
56+
self.state += 1
57+
58+
59+
if __name__ == '__main__':
60+
for test in (tester, tester1, tester2, tester3, tester4):
61+
f = test(0)
62+
f('name: %s, state:' % test.__name__)
63+
f('name: %s, state:' % test.__name__)
64+
f('name: %s, state:' % test.__name__)
65+
f('name: %s, state:' % test.__name__)
66+
print()
67+
print('done')

0 commit comments

Comments
 (0)