Why do closures do this?

Terry Reedy tjreedy at udel.edu
Sun Aug 28 18:26:18 CEST 2011

On 8/28/2011 10:04 AM, Thomas Jollans wrote:

> This does not do what you'd like it to do. But let's assume that, it
> did, that Python, when encountering a function definition inside a
> function, "froze" the values of nonlocal variables used in the new
> function, from the point of view of that function — that *might* be more
> intuitive, at least in certain situations. However, what if you wanted a
> closure to access a nonlocal variable that changes - acting differently
> depending on what has since happened in the parent function.
> That may not be as common, but it is a perfectly plausible situation,
> and the hack required to support that behaviour in a Python that acts as
> you had expected it to, a surrogate namespace using a class, list, or
> dict, is infinitely more cryptic and ugly than the default-parametre hack.

Or, what if the nonlocal name is not even defined when the closure is.

 >>> def f():
	def g(): print(a)
	a = 3

 >>> f()

Note that global names also do not have to be defined when a function 
using them is compiled. The current situation is that nonlocal and 
global names are treated the same way. This makes normal and nested 
functions as much the same as possible. This is intentional. It would be 
extremely disconcerting if moving code that contains a def into or out 
of a wrapping function radically changed its behavior more than is 
absolutely necessary.

Terry Jan Reedy

More information about the Python-list mailing list