0

Possible Duplicate:
Creating lambda inside a loop

In the code below, invoking any member of the returned array of closures prints the number 4.

def go():
    x = []
    for i in range(5):
        def y(): print i
        x.append(y)

    return x

I would like each member of the closure to print the number that i was when the closure was defined.

Community
  • 1
  • 1
Terrence Brannon
  • 4,760
  • 7
  • 42
  • 61

1 Answers1

4

One way around this is to use default arguments:

def y(i=i): 
    print i

Default arguments are evaluated when the function is created, not called, so this works as you'd expect.

>>> i = 1
>>> def y(i=i): print i
... 
>>> i = 2
>>> y()
1

A little extra info just for fun:

If you're curious what the defaults are, you can always inspect that with the .func_defaults attribute (__defaults__ in python3.x):

>>> y.func_defaults
(1,)

This attribute is also writeable, so you can in fact change the defaults after the function is created by putting a new tuple in there.

mgilson
  • 300,191
  • 65
  • 633
  • 696