The Problem of variable referenced in the nested function

763 views Asked by At

There are tow simple functions owning nested function, as follows:

def a():
    abc = 1
    def write():
        print abc
    write()

def b():
    abc = 1
    def write():
        print abc
        abc += 1
    write()

The difference between these tow is just that I tried to change the value of the variable.

When I run a(),that's ok.

When I run b(),I get back the error "UnboundLocalError: local variable 'abc' referenced before assignment"

What is the reason?

1

There are 1 answers

1
atru On

The problem you're encountering is in the scope of variables. The nested functions in your program have their own local namespace/scope different from the outer function that calls them.

According to Python documentation

If a name is declared global, then all references and assignments go directly to the middle scope containing the module’s global names. Otherwise, all variables found outside of the innermost scope are read-only (an attempt to write to such a variable will simply create a new local variable in the innermost scope, leaving the identically named outer variable unchanged).

Meaning that if you instead try this:

def b():
    abc = 1
    global abc
    print abc
    def write():
        global abc
        abc += 1
        print abc
    write()
    print abc

your function b will run without errors. This also means that the value of abc will increase globally and become 2 after calling write().

If you don't declare your abc variable as global, it will be read-only for the nested function write(). write() won't be able to change it but it will be able to print it, or locally re-assign it. The following also works because it first reassigns the value of abc to another, local variable and then changes that variable,

def a():
    abc = 1
    def write():
        print abc
        abc2 = abc
        abc2 += 1
        print abc2
    write()

You can print local variables in a given scope using print locals().