Alternative notation for defining closures in python; It avoids packing closure variables into containers by assigning attributes to the inner function.
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 | # nice and clean closure notation
def get_counter_neat():
def f():
f.x += 1
return f.x
f.x = 0
return f
# traditional, not_so_neat closure notation
def get_counter_traditional():
x = [0]
def f():
x[0] += 1
return x[0]
return f
#### EXAMPLE ###########################################################
cnt_a = get_counter_neat()
cnt_b = get_counter_neat()
print cnt_a() # >>> 1
print cnt_a() # >>> 2
print cnt_a() # >>> 3
print cnt_b() # >>> 1
print cnt_a() # >>> 4
print cnt_b() # >>> 2
print cnt_b() # >>> 3
|
Tags: programs
Updating closure variables. I think it's worth noting that this also makes it easy to update the closure variables since they're attributes of the function:
Possible fix. Probably this is what you want:
cnt_a = get_counter_neat()
cnt_b = get_counter_traditional()
I'm curious why you wouldn't just use a class:
It's also just as easy to specify starting and increment values: