Misunderstanding about closures

Robert Brewer fumanchu at amor.org
Mon Jun 7 00:12:25 EDT 2004


Alexander May wrote:
> When I define a function in the body of a loop, why doesn't 
> the function "close" on the loop variable?
> 
> >>> l=[]
> >>> for x in xrange(10):
> ...   def f():
> ...     return x
> ...   l.append(f)
> ...
> >>> for f in l:
> ...     f()
> ...
> 9
> 9
> 9

...because "for" does have it's own scope. The 'x' which is bound in the
'for' statement persists in locals(), and it equals 9 after the 'for'
terminates. Calling each f() simply looks up x in locals() each time;
there's nothing going on in f() which tells Python that x should be in
f's scope. That would require an assignment to x within f, usually.

You could trot out the 'default arg' hack to work around this:

>>> l = []
>>> for x in xrange(10):
... 	def f(y=x):
... 		return y
... 	l.append(f)
... 	
>>> x
9
>>> [f() for f in l]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


Robert Brewer
MIS
Amor Ministries




More information about the Python-list mailing list