When to use nonlocal keyword?

Question:

I don’t understand why I can use series variable here:

def calculate_mean():
    series = []
    def mean(new_value):
        series.append(new_value)    
        total = sum(series)
        return total/len(series)
    return mean

But I can’t use count and total variables here (variable referenced before assignment):

def calculate_mean():
    count = 0
    total = 0
    def mean(value):
        count += 1
        total += value
        return total/count
    return mean

It works only if I use nonlocal keyword like this:

def calculate_mean():
    count = 0
    total = 0
    def mean(value):
        nonlocal count, total
        count += 1
        total += value
        return total/count
    return mean

This is how I use calculate_mean()

mean  = calculate_mean()
print(mean(5))
print(mean(6))
print(mean(7))
print(mean(8))
Asked By: user3565923

||

Answers:

What you are facing there is that in one case, you have in the vareiable a mutable object, and you operate on the object (when it is a list) – and in the other case you are operating on an imutable object and using an assignment operator (augmented assingment +=) .

By default, Python locates all non-local variables that are read and use then accordingly – but if a variable is assigned to in the inner scope, Python assumes it is a local variable (i.e. local to the inner function), unless it is explicitly declared as nonlocal.

Answered By: jsbueno
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.