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