Python: Modifying a Counter in a Closure
I helped a fellow Pythonista with a problem today, and it reminded me that a lot of people might not know about the trick of using a list to box variables within a closure. If that doesn't make sense, read the code below:
"""Create a counter starting at ``start``."""
# The value "curr" needs to be wrapped in a list. Otherwise, when
# "+=" is used in "inc", Python binds the variable at that scope
# instead of at this scope. We don't want to redefine a variable at
# the inner scope. We want to modify the variable at this outer
# scope. Java programmers would call this "boxing", but they would
# use an Integer instance instead of a list.
curr = [start]
"""Increment the counter and return the new value."""
curr += 1
if __name__ == '__main__':
c = counter(5)
for i in range(3):
print c() # Prints 6 7 8.