1

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

Andy L.
  • 24,909
  • 4
  • 17
  • 29
  • I don’t worry about such things. What is in a name? A closure by any other name would be just as functional. – quamrana Dec 28 '19 at 22:00

1 Answers1

1

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.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • 1
    Following the that example he states 3 reasons: `Python supports closures: functions that refer to variables from the scope in which they were defined. This is why the helper function is able to access the group argument to sort_priority.......This is why the return value from the helper closure causes the sort order to have two distinct groups.`. It is `Item 15: Know How Closures Interact with Variable Scope`. Pearson provides sample pages of the book here: https://ptgmedia.pearsoncmg.com/images/9780134034287/samplepages/9780134034287.pdf. – Andy L. Dec 28 '19 at 23:11
  • Brett's follow-ups from that example indicates that he meant closure happened in `helper`, so I don't think he is mistaken. His analysis is thoughtful, but this closure part is bugging me and makes me doubt my understanding of closure. I really wish his definition of closure is consistent with others because I really like his book. Thanks for the answer. I wait for a few days to see any different insights. Upvoted :) +1 – Andy L. Dec 29 '19 at 06:28
  • 1
    So, just as I said: Slatkin is using a definition of closure that is slightly more broad than the one you referenced, and he presents it in the book. And he is referring to `helper()` being able to access variables from the context of its definition when it is called from a place where they are out of scope. I note that this is consistent with [the Wikipedia definition of the term](https://en.wikipedia.org/wiki/Closure_(computer_programming)). I'm afraid it's not unusual for the same word to be defined a bit differently by different people. – John Bollinger Dec 29 '19 at 14:43