-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocal_counter.py
More file actions
38 lines (31 loc) · 839 Bytes
/
Copy pathlocal_counter.py
File metadata and controls
38 lines (31 loc) · 839 Bytes
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
#!/usr/bin/env python3
""" Local function mimicing a generator """
def create_counter(n):
""" (int) -> function
Creates a counting function that counts up to <n>
Returns it's own local function counter()
"""
count = 0 # Init
def counter():
"""
Increaments the outer var unless it has reached its's limit
NOTE:
'Remembers' the value of it's enclosing function's local var count
thue, it represents a closure
"""
nonlocal count
if count < n:
count += 1
return count
return counter
if __name__ == '__main__':
cntr = create_counter(4)
print(cntr())
print(cntr())
print(cntr())
print(cntr())
print(cntr())
print(cntr())
print(cntr())
print(cntr())
print(cntr())