in reply to Re: Closures and scope of lexicals
in thread Closures and scope of lexicals

Tho python is still different IIRC.

There is no block scope, variables live in a function or a file.

In order to create a list of closure functions in a loop closing over different variables - like in the OP's first example - one would need to call an explicit generator function, having the var in its scope and returning the closure.

Cheers Rolf
(addicted to the Perl Programming Language :)
see Wikisyntax for the Monastery

Replies are listed 'Best First'.
Re^3: Closures and scope of lexicals
by ikegami (Patriarch) on Oct 31, 2024 at 14:25 UTC

    But it's supposed to be file-scoped. $i is scoped to the file in the OP's code. Your suggested change would make the code different than the OP's code.

      I was referring to his first example which prints 123

      That's more complicated to achieve in Python IMHO.

      Edit

      I think JS had a similar effect with var , that's why let was introduced

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      see Wikisyntax for the Monastery

        I didn't translate the first snippet. The question is about the second snippet. The OP asked if its behaviour is a quirk. I showed that it's not by showing that the behaviour is consistent across many languages.

        Yes, JS's var is function-scoped at the narrowest. It's even retroactive such that

        foo = 1; var foo;
        is equivalent to
        var foo; foo = 1;