On 22/06/13 17:04, Peter Otten wrote:
This technique of nesting a function inside another function ("closure")
To be pedantic, not all nested functions are closures. Here's one which is not:
def outer(arg):
def inner(x):
return x + 1
assert inner.__closure__ is None
return inner(arg)
In this case, the inner function does not refer to any variables defined in the
outer function. Instead, it is explicitly passed the value it needs as an
argument.
Here's one which is a closure:
def outer(arg):
def inner():
return arg + 1
assert inner.__closure__ is not None
return inner()
The function attribute "__closure__" is set to None for regular functions. For closures,
it is set to a bunch of stuff needed for the inner function to work correctly. (No user serviceable
parts inside.) Basically, the inner function needs to carry around with it a little piece of its
environment, so it can retrieve the value of "arg" when required.
--
Steven
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor