[Python-ideas] Tweaking closures and lexical scoping to include the function being defined
Jan Kaliszewski
zuo at chopin.edu.pl
Wed Sep 28 23:57:47 CEST 2011
Terry Reedy dixit (2011-09-27, 21:17):
> defining a function
> inside a loop magically causes define-time binding of names in the
> body.
No, it does not cause such a binding. That is one of the cases the
proposition of this or that early-binding syntax comes back repeatedly:
def strangish_factorission():
chairs = []
for spam in (1,2,3,4,5):
def comfy_chair(fmt):
# we naively try to make use of early binding here
# but there is no such binding here
result = fmt % spam
return result
chairs.append(comfy_chair)
return chairs
for comfy_chair in strangish_factorission():
print comfy_chair('%d'),
-- will print "5 5 5 5 5", not "1 2 3 4 5".
To obtain the latter you need to use eigher default argument hack (which
is ugly and unsafe in some situations) or a closure (which for now needs
another nested scope, which is even worse in terms of readability).
Cheers,
*j
More information about the Python-ideas
mailing list