Comment

Comment by BoppreH

The same problem frequently bites me in Python too:

    functions = []

    for i in range(10):
        functions.append(lambda: print(f'Hello {i}'))
    
    for fn in functions:
        fn()

    # Hello 9
    # Hello 9
    # Hello 9
    # Hello 9
    # Hello 9
    # Hello 9
    # Hello 9
    # Hello 9
    # Hello 9
    # Hello 9
I find it one of Python's biggest warts because it's silent, hard to troubleshoot (especially the first time!), and like in Go the most straightforward fix looks like a mistake (i=i):

    for i in range(10):
        functions.append(lambda i=i: print(f'Hello {i}'))
I guess this is a lesson in designing language semantics that match people's intuitions, and learning from previous languages' mistakes.
parent BoppreH 4 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton