I'm trying to accomplish something like the following:
def counter():
_n = 0
def _increase():
_n += 1
return _n
return _increase
The above example should behave like this:
>>> c = counter()
>>> c()
1
>>> c()
2
>>> c()
3
However, when trying to reproduce this, I get the following error:
>>> c = counter()
>>> c()
UnboundLocalError: local variable '_n' referenced before assignment
It looks like it's trying to find the variable in the local scope, so I changed my code to the following:
def counter():
_n = 0
def _increase():
global _n
_n += 1
return _n
return _increase
It appears that it's able to locate it just fine now, but apparently it's uninitialized, even though I'm executing _n = 0
before even declaring the function.
>>> c = counter()
>>> c()
NameError: name '_n' is not defined
Clearly I'm doing something wrong and I'm not aware of a specific Python behavior in this case.
What am I missing here?