Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid closure in Python's lambda function

Consider this short code snippet:

class X:
    pass

xs = []
for s in ("one", "two", "three"):
    x = X()
    x.f = lambda: print(s)
    xs.append(x)

for x in xs:
    x.f()

It outputs:

three
three
three

I thought the result should be like this instead:

one
two
three

Why is that not the actual result?

like image 819
grześ Avatar asked Jul 31 '26 15:07

grześ


1 Answers

Your lambda function holds reference to s, hence the last assigned value to s is printed when called outside that for loop. Try the below code for your expected behaviour. Here a copy of that existing reference s is created in v as function argument and that value is printed inside the function f.

class X:
    pass

xs = []
for s in ("one", "two", "three"):
    x = X()
    def f(v=s): print(v)
    x.f = f
    xs.append(x)

for x in xs:
    x.f()

Output:

one
two
three
like image 192
Praveenkumar Avatar answered Aug 02 '26 05:08

Praveenkumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!