I\'m trying to build a counter in python with the property of closure. The code in the following works:
def generate_counter():
CNT = [0]
def add_one
It doesn't have to be a list, it just has to be an mutable object which you mutate, not reassign.
From the docs:
If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
Thus, in your second example, x
is considered local (to the inner function), and, after your first assignment, you're shadowing the outer 'x'.
On the other hand, in the first example (since you don't assign a value to CNT
) it operates on the CNT
defined in the outer function.