I’ve been reading
Fluent Pythonrecently, and picked up a few important points inPythonto understand. This assumes the reader has somePythonbackground.
A Short Piece of Code
1 | In [1]: def make_averager(): |
The return value of make_averager in the code above is a function averager defined inside it.
So the return value should be callable — hence avg(1), avg(10).
This all seems natural.
Is Returning a Function a Closure?
In C/C++ there are also function pointers, which can be returned too, yet we don’t call that a closure.
So What Exactly Is a Closure?
Note the series array in the code. This array is defined in make_averager; after
In [2]: avg = make_averager() has been called, other functions can no longer see or use this variable
(if you don’t follow me, go search: variable scope!).
But when we call In [3]: avg(1), the function nested inside make_averager below must have executed:
1 | def averager(new_value): |
It used the series array — yes, it really used it. It used a variable that other functions cannot use.
The scope of the series array extended into the averager function, or rather, the averager function recorded the
address of that variable and thereby manipulated it. Now the variable’s scope is wrapped up by the inner function averager —
only then can it be called a closure.
The Explanation in Fluent Python
English excerpt from: fluent-python-2015.pdf P195
To summarize: a closure is function that retains the bindings of the free variables that exist when the function is defined, so that they can be used later when the function is invoked and the defining scope is no longer available.
Note that the only situation in which a function may need to deal with external variables
A closure is a function that can retain bindings to free variables — variables that really only exist when the function is defined. But with those bindings in hand, they can still be read and written when the function is invoked, even though the defining scope is gone.
- I hope I’ve explained the concept of closures clearly; questions are welcome.