嵌套函数作用域的 Unbound LocalError

我有这样的代码(简化版) :

def outer():
ctr = 0


def inner():
ctr += 1


inner()

ctr会导致一个错误:

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

我该怎么补救?我以为嵌套显微镜可以让我这么做。我试过“全球化”,但还是不行。

16341 次浏览

How about declaring ctr outside of outer (i.e. in the global scope), or any other class/function? This will make the variable accessible and writable.

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.

The Explanation

Whenever a value is assigned to a variable inside a function, python considers that variable a local variable of that function. (It doesn't even matter if the assignment is executed or not - as long as an assignment exists in a function, the variable being assigned to will be considered a local variable of that function.) Since the statement ctr += 1 includes an assignment to ctr, python thinks that ctr is local to the inner function. Consequently, it never even tries to look at the value of the ctr variable that's been defined in outer. What python sees is essentially this:

def inner():
ctr = ctr + 1

And I think we can all agree that this code would cause an error, since ctr is being accessed before it has been defined.

(See also the docs or this question for more details about how python decides the scope of a variable.)

The Solution (in python 3)

Python 3 has introduced the nonlocal statement, which works much like the global statement, but lets us access variables of the surrounding function (rather than global variables). Simply add nonlocal ctr at the top of the innerfunction and the problem will go away:

def outer():
ctr = 0


def inner():
nonlocal ctr
ctr += 1


inner()

The Workaround (in python 2)

Since the nonlocal statement doesn't exist in python 2, we have to be crafty. There are two easy workarounds:

  • Removing all assignments to ctr

    Since python only considers ctr a local variable because there's an assignment to that variable, the problem will go away if we remove all assignments to the name ctr. But how can we change the value of the variable without assigning to it? Easy: We wrap the variable in a mutable object, like a list. Then we can modify that list without ever assigning a value to the name ctr:

    def outer():
    ctr = [0]
    
    
    def inner():
    ctr[0] += 1
    
    
    inner()
    
  • Passing ctr as an argument to inner

    def outer():
    ctr = 0
    
    
    def inner(ctr):
    ctr += 1
    return ctr
    
    
    ctr = inner(ctr)