Andy L.
Andy L.

Reputation: 25239

Does Python closure require the outer scope going out of scope(i.e. ended)

As explain in this SO answer A closure occurs when a function has access to a local variable from an enclosing scope that has finished its execution. As I understand a function scope is finished when it returns. Several books on python closure always have examples on closure defining a nested function and returning it at the end to signify the ending of the outer scope. Such as Fluent Python by Ramalho

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

Book Introducing Python by Lubanovic

def knights2(saying):
    def inner2():
        return "We are the knights who say: '%s'" % saying
    return inner2

I then stumble upon the book Effective Python by Brett Slatkin. His example of closure:

def sort_priority(values, group):
    def helper(x):
        if x in group:
            return (0, x)
        return (1, x)
    values.sort(key=helper)

numbers = [8, 3, 1, 2, 5, 4, 7, 6]
group = {2, 3, 5, 7}
sort_priority(numbers, group)

Brett says closure happen in helper function. helper got called inside of values.sort(key=helper). As I understand the scope of sort_priority has not ended when it reaches to the line values.sort(key=helper). Why does he say closure occurring here?

I only wonder about the closure aspect of Brett's example. I already know/understand how sort_priority and helper work

Pearson provides the sample pages of the book here. Luckily, sample pages have the part I mentioned. It is Item 15: Know How Closures Interact with Variable Scope

Upvotes: 1

Views: 92

Answers (1)

John Bollinger
John Bollinger

Reputation: 180286

As I understand the scope of sort_priority has not ended when it reaches to the line values.sort(key=helper). Why does he say closure occurring here?

Supposing that it is not an outright mistake, Slatkin must be using a different definition of "closure". Since the code presented is an example, I presume it accompanies a definition, which you should compare carefully with the one you quoted.

I suppose that Slatkin's idea revolves around helper() being able to access the group variable of the surrounding context when it is called by values.sort(), where that variable is not in scope. This is at least akin to the conventional definition of a closure -- the function carries with it the ability to reference data belonging to the context of its definition. I don't think I would agree that it fully meets the usual criteria for a closure, but do not let that distract you from the essence of the technique that Slatkin is trying to teach.

Upvotes: 1

Related Questions