When Closure get external variable's value?
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Tue Dec 19 16:14:05 EST 2006
Huayang Xia a écrit :
> I'm confused. What is the definition of closure.
>
> I'm not sure if it's correct, I get the definition from wikipedia:
>
> "A closure typically comes about when one function is declared entirely
> within the body of another, and the inner function refers to local
> variables of the outer function. At runtime, when the outer function
> executes, a closure is formed. It consists of the inner function's code
> and references to any variables in the outer function's scope that the
> closure needs."
You skipped the first and most important sentence:
"In programming languages, a closure is a function that refers to free
variables in its lexical context."
IOW, a closure is a function that carry it's own environment. In the
following code, the function returned by make_adder is a closure :
def make_adder(adding):
def adder(num):
return num + adding
return adder
add_three = make_adder(3)
print add_three(4)
=> 7
> I agree it is not declaration, it's definition. However it's closure
> based on the above definition. It uses free variable.
Actually, it uses a variable defined in the enclosing scope. But as long
as it's also executed in the same enclosing scope, it's just a nested
function.
> Or you mean it's
> a closure only when the outer function returns it and be exposed to
> external world?
Bingo.
More information about the Python-list
mailing list