I have code like this (simplified):
def outer():
ctr = 0
def inner():
ctr += 1
inner()
But ctr causes an error:
Traceback (most recent call last):
File "foo.py", line 9, in <module>
outer()
File "foo.py", line 7, in outer
inner()
File "foo.py", line 5, in inner
ctr += 1
UnboundLocalError: local variable 'ctr' referenced before assignment
How can I fix this? I thought nested scopes would have allowed me to do this. I’ve tried with ‘global’, but it still doesn’t work.
If you’re using Python 3, you can use the
nonlocalstatement to enable rebinding of a nonlocal name:If you’re using Python 2, which doesn’t have
nonlocal, you need to perform your incrementing without barename rebinding (by keeping the counter as an item or attribute of some barename, not as a barename itself). For example:and of course use
ctr[0]wherever you’re using barectrnow elsewhere.