How does a non-local keyword work?

In the below code

def makeAverage():
    series = []
    def average(newValue):
        series.append(newValue)
        total = sum(series)
        return total/len(series)
    return average

      

the python interpreter doesn't expect to series

be nonlocal

in average()

.

But in the below code

def makeAverage():
    count = 0
    total = 0
    def average(newValue):
        nonlocal count, total
        count += 1
        total += newValue
        return total/count
    return average

      

Question:

Why is the python interpreter expecting count

and total

declared nonlocal

in average()

?

+3


source to share


1 answer


A variable is considered local to a function if you assign it anywhere in that function and you do not mark it otherwise (with global

or nonlocal

). In your first example, there is no assignment series

inside average

, so it is not considered local to average

, so the version from the included function is used. In the second example, there is purpose total

and count

inside average

, so they should be marked nonlocal

in order to access them from closing function. (Otherwise, you will get an UnboundLocalError because it average

tries to read their values ​​before assigning them the first time.)



+3


source







All Articles