UnboundLocalError with nested function scopes

If you’re using Python 3, you can use the nonlocal statement to enable rebinding of a nonlocal name:

def outer():
    ctr = 0

    def inner():
        nonlocal ctr
        ctr += 1

    inner()

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:

...
ctr = [0]

def inner():
    ctr[0] += 1
...

and of course use ctr[0] wherever you’re using bare ctr now elsewhere.

Leave a Comment