0

Why do the functions in the first code example take reference to object i, but in the second code example, object i is copied into the argument of the print function?

i = 10
f = lambda: click_toggle( i )
i = 20
g = lambda: click_toggle( i )
f()
g()
def get_new_func( idx ):
    def click_toggle():
        print( idx )
    return click_toggle

i = 30
f2 = get_new_func( i )
i = 40
g2= get_new_func( i )
f2()
g2()

In the first case we get

20
20

In the second

30
40

Why is the second case not showing the same behavior as the first? How do I copy the object to the lambda in the first case?

  • TL;DR: *At the time you call the function*, the variable's value is looked up. It's not hard baked into the function. When creating a new function in the second example, you're creating a closure with a captured value, because you're not looking up a global variable but a local variable. – deceze Jan 20 '23 at 08:08

0 Answers0