Skip to content

Commit 3ced5a3

Browse files
committed
python3 nonlocal
1 parent 2a0541e commit 3ced5a3

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""
2+
Keeping track all the series is not efficient
3+
Just keep the count and total.
4+
Use nonlocal in Python3
5+
* Flag a variable as a free variable even it is assigned
6+
* a new value within the function
7+
* Otherwise, immutable types in closure can never be assigned,
8+
* because it will be marked as local
9+
Workarounds of nonlocal in Python2
10+
* Python2 lacks nonlocal keyword
11+
* Store the variables the inner functions need to change as items
12+
* or attributes of some mutable object, like dict or simple instance
13+
* and bind that object to a free variable
14+
>>> avg = make_averager()
15+
>>> avg(10)
16+
10.0
17+
>>> avg(11)
18+
10.5
19+
>>> avg(12)
20+
11.0
21+
"""
22+
23+
def make_averager():
24+
count = 0
25+
total = 0
26+
27+
def averager(new_value):
28+
"""Without nonlocal, UnboundLocalError will be raised."""
29+
nonlocal count, total
30+
count += 1
31+
total += new_value
32+
return total / count
33+
return averager
34+
35+
if __name__ == "__main__":
36+
import doctest
37+
doctest.testmod()

0 commit comments

Comments
 (0)