← Back to context

Comment by b3orn

14 days ago

It's unrelated to the for loop, the for only changes the variable, there are other ways you can do that and you'll run into the same "oddity"

    def test():
        n = 0
        def a():
            return n
        n = 1
        def b():
            return n
        return a, b

    a, b = test()
    a() == 1
    b() == 1

> for changes the variable

That's a design decision, not a law of nature. JS 'for let' lacks this problem; probably the committee would have named it just 'for' if not for legacy.

I get why it behaves like this, but I find it odd that Python claims to have "lexical scoping". This is not lexical (as you read it). This is based on somewhat hidden reference lookups.