Misunderstanding about closures

Alexander May alex-news-deleteme at comcast.net
Sun Jun 6 23:27:22 EDT 2004


When I define a function in the body of a loop, why doesn't the function
"close" on the loop vairable?  See example below.

Thanks,
Alex

C:\Documents and Settings\Alexander May>python
Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> l=[]
>>> for x in xrange(10):
...   def f():
...     return x
...   l.append(f)
...
>>> l
[<function f at 0x008E66F0>, <function f at 0x008E6AB0>, <function f at
0x008EC130>, <function f at 0x008EC170>, <functi
on f at 0x008EC1B0>, <function f at 0x008EC1F0>, <function f at 0x008EC230>,
<function f at 0x008EC270>, <function f at
0x008EC2B0>, <function f at 0x008EC2F0>]
>>> for f in l:
...     f()
...
9
9
9
9
9
9
9
9
9
9

On the other hand, the following works as I expected.

>>> l=[]
>>> def makef(x):
...   def f():
...     return x
...   return f
...
>>> for x in xrange(10):
...   l.append(makef(x))
...
>>> l
[<function f at 0x008E6AB0>, <function f at 0x008EC330>, <function f at
0x008EC1F0>, <function f at 0x008EC230>, <functi
on f at 0x008EC270>, <function f at 0x008EC2B0>, <function f at 0x008EC0F0>,
<function f at 0x008EC370>, <function f at
0x008EC3B0>, <function f at 0x008EC3F0>]
>>> for f in l:
...     f()
...
0
1
2
3
4
5
6
7
8
9
>>>





More information about the Python-list mailing list