Hacker News .hnnew | past | comments | ask | show | jobs | submitlogin

I have run into this problem in Python too, but not recently. I'm not sure if Python has changed or if I just caught on to the problem.

This should be enough to show that it still can wind up as a problem in Python:

    funcs = [(lambda: x) for x in range(3)]
    funcs[0]()  # outputs: 2


That is correct.

Python used to be worse; it used to share scope outside the list comprehension.


It still does for regular loops right?


Yeah loops don't get their own scopes (unless you add one using this thing I made as a joke: https://github.com/davisyoshida/360blockscope)


GPT-4 says: The behavior you're observing is due to the late binding nature of closures in Python. When you use a lambda inside a list comprehension (or any loop), it captures a reference to the variable x, not its current value. By the time you call funcs[0](), x has already been set to the last value in the range, which is 2.

To get the desired behavior, you can pass x as a default argument to the lambda:

   funcs = [(lambda x=x: x) for x in range(3)]
   funcs[0]() # outputs 0




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: