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