[Python-ideas] Tweaking closures and lexical scoping to include the function being defined

Greg Ewing greg.ewing at canterbury.ac.nz
Tue Sep 27 07:05:47 CEST 2011

Terry Reedy wrote:
> One of the explicit reasons for introducing closures 
> defined by nesting was to reduce default value use.

Indeed, and the question that needs to be asked is:
Why does the default argument hack persist, when we
now have a lexical scope system that's just as good
as other languages such as Scheme and Haskell have,
yet no such kludge seems to be needed in those languages?

I don't believe it's because there's anything wrong
with our functions or closures. Rather, it's a symptom
of lingering deficiencies in *other* parts of the

For example, when someone writes

     for i in things:
         def f():

and get surprised by the result, he's effectively
assuming that the for-loop creates a new binding for
i each time around. He may not *realise* he's assuming
that, but he is.

Given that people seem to unconsciously make that
assumption, perhaps we should consider making the
for-loop actually behave that way. There's a precedent
for this -- list comprehensions used to leak their
loop variable into the surrounding scope, but that
was eventually changed.

Another point I'd like to make is that I don't think
Nick's proposal, or any spelling variation of it, helps
all that much in this case. Having to do *anything*
special in or around the function to work around this
problem is something of a kludge, especially if it
involves writing anything as tautological-looking as
"i = i".


More information about the Python-ideas mailing list